How do you use the flutter/dart package spreadsheet_decoder? - flutter

When I try to use the package 'spreadsheet_decoder' in my flutter app like so:
var file = Uri.file('spreadsheets/Contact_list.xlsx');
var bytes = File.fromUri(file).readAsBytesSync();
var decoder = SpreadsheetDecoder.decodeBytes(bytes);
where I created a folder called spreadsheets inside the app and added it to the pubspec.
I got the following error:
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: FileSystemException: Cannot open file, path = 'spreadsheets/Contact_list.xlsx' (OS Error: No such file or directory, errno = 2)
#0 _File.throwIfError (dart:io/file_impl.dart:645:7)
#1 _File.openSync (dart:io/file_impl.dart:489:5)
#2 _File.readAsBytesSync (dart:io/file_impl.dart:549:18)
#3 getData (package:cvr/extract_excel.dart:8:34)
#4 _TransferScreenState.transferPeopleFromExcelToFirebase (package:cvr/utilities/transfer_data.dart:35:5)
<asynchronous suspension>
#5 _TransferScreenState.build.<anonymous closure> (package:cvr/utilities/transfer_data.dart:52:11)
#6 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
#7 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
#8 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
#9 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.<…>
If I use the exact same code in a stand alone dart file and run it separately I do not get this error.
Does anyone know where I can save the excel document and what path I should use to access it?

You can use https://pub.dev/packages/path_provider and get temp directory via getTemporaryDirectory()
You can copy paste run full code below
and need to put your file in /data/user/0/your_domain.your_project/cache/test.xlsx
code snippet
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
var file = '${tempDir.path}/test.xlsx';
print('file full path $file');
var bytes = File(file).readAsBytesSync();
var decoder = SpreadsheetDecoder.decodeBytes(bytes, update: true);
output of full code
I/flutter ( 515): file full path /data/user/0/your_domain.your_proejct/cache/test.xlsx
I/flutter ( 515): wosksheet1
I/flutter ( 515): 1
I/flutter ( 515): 2
I/flutter ( 515): [test]
I/flutter ( 515): [123]
full code
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:spreadsheet_decoder/spreadsheet_decoder.dart';
import 'package:path_provider/path_provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() async {
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
var file = '${tempDir.path}/test.xlsx';
print('file full path $file');
var bytes = File(file).readAsBytesSync();
var decoder = SpreadsheetDecoder.decodeBytes(bytes, update: true);
for (var table in decoder.tables.keys) {
print(table);
print(decoder.tables[table].maxCols);
print(decoder.tables[table].maxRows);
for (var row in decoder.tables[table].rows) {
print("$row");
}
setState(() {
_counter++;
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Try using the Uri.parse or Uri.tryParse mehod
Example Code:
var readbytes = File.fromUri(Uri.parse('path/THISisCOOL.xlsx')).readAsBytesSync();

Related

Flutter: Geolocator gives wrong location

When I execute, (click on the "show Longitude and Latitude" button) I have two problems, a wrong position and an error:
**W/GooglePlayServicesUtil( 5181): com.example.geolocalisation_youtube requires the Google Play Store, but it is missing.
I/flutter ( 5181): 10681894.898369517
I/flutter ( 5181): long c.longitude
I/flutter ( 5181): 37.421998333333335
E/flutter ( 5181): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(IO_ERROR, A network error occurred trying to lookup the supplied coordinates (latitude: 37.421998, longitude: -122.084000)., null, null)
E/flutter ( 5181): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:653:7)
E/flutter ( 5181): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:296:18)
E/flutter ( 5181): <asynchronous suspension>
E/flutter ( 5181): #2 MethodChannelGeocoding.placemarkFromCoordinates (package:geocoding_platform_interface/src/implementations/method_channel_geocoding.dart:56:24)
E/flutter ( 5181): <asynchronous suspension>
E/flutter ( 5181): #3 _MyHomePageState.build.<anonymous closure> (package:geolocalisation_youtube/main.dart:84:47)
E/flutter ( 5181): <asynchronous suspension>
**
Here’s the code:
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:geocoding/geocoding.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future getPosition() async{
bool service= await Geolocator.isLocationServiceEnabled();
LocationPermission per= await Geolocator.checkPermission();
if (per==LocationPermission.denied){
per= await Geolocator.requestPermission();
if(per!=LocationPermission.denied){
}
}
print(service);
print("---------------");
print(per);
print("---------------");
if(!service ){
AwesomeDialog(
context: context,
title: "services",
body:
Text("service is enabled")
)..show();
}
}
Future <Position> getLatandLong() async{
return await Geolocator.getCurrentPosition().then((value) => value);
}
#override
void initState(){
getPosition();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children: [
Container(
height: 500,
width:400 ,
),
ElevatedButton(
onPressed: () async{
var c = await getLatandLong();
var distance= await Geolocator.distanceBetween(c.latitude, c.longitude, 28.033886, 1.659626);
print(distance);
print("long c.longitude ");
print(c.latitude);
List<Placemark> placemarks = await placemarkFromCoordinates(c.latitude, c.longitude);
print(placemarks[0].administrativeArea);
},
child: Text(" show Longitude and Latitude"))
],
),
);
}
}
I got this error on the latest version of Android Studio.

No Firebase App '[Default]' error but firebase is already initialized

Every time I try to run my flutter app that has been previously working, I get No Firebase App '[Default]' error. I have this project connected to my GitHub and I downloaded a different version and it seemed to work fine, so I thought to revert my main repo to that commit, and then the same thing happened again. I did a git compare and found no differences in the files, which made it hard to find out what was happening.
Error caught in the debug console
════════ Exception caught by widgets library ═══════════════════════════════════
The following FirebaseException was thrown building FutureBuilder<FirebaseApp>(dirty, state: _FutureBuilderState<FirebaseApp>#d30ed):
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
The relevant error-causing widget was
FutureBuilder<FirebaseApp>
package:mynotes/main.dart:105
When the exception was thrown, this was the stack
#0 MethodChannelFirebase.app
package:firebase_core_platform_interface/…/method_channel/method_channel_firebase.dart:193
#1 Firebase.app
package:firebase_core/src/firebase.dart:53
#2 FirebaseAuth.instance
package:firebase_auth/src/firebase_auth.dart:38
#3 Setup.build.<anonymous closure>
package:mynotes/main.dart:110
#4 _FutureBuilderState.build
package:flutter/…/widgets/async.dart:615
#5 StatefulElement.build
package:flutter/…/widgets/framework.dart:4919
#6 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4806
#7 StatefulElement.performRebuild
package:flutter/…/widgets/framework.dart:4977
#8 Element.rebuild
package:flutter/…/widgets/framework.dart:4529
#9 BuildOwner.buildScope
package:flutter/…/widgets/framework.dart:2659
#10 WidgetsBinding.drawFrame
package:flutter/…/widgets/binding.dart:891
#11 RendererBinding._handlePersistentFrameCallback
package:flutter/…/rendering/binding.dart:370
#12 SchedulerBinding._invokeFrameCallback
package:flutter/…/scheduler/binding.dart:1146
#13 SchedulerBinding.handleDrawFrame
package:flutter/…/scheduler/binding.dart:1083
#14 SchedulerBinding._handleDrawFrame
package:flutter/…/scheduler/binding.dart:997
#18 _invoke (dart:ui/hooks.dart:151:10)
#19 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:308:5)
#20 _drawFrame (dart:ui/hooks.dart:115:31)
(elided 3 frames from dart:async)
════════════════════════════════════════════════════════════════════════════════
Main.dart
import 'dart:io';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_phoenix/flutter_phoenix.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:mynotes/constants/routes.dart';
import 'package:mynotes/services/auth/auth_service.dart';
import 'package:mynotes/services/auth/auth_user.dart';
import 'package:mynotes/services/hive/boxes.dart';
import 'package:mynotes/services/hive/settings_service.dart';
import 'package:mynotes/themes/themes.dart';
import 'package:mynotes/views/forgot_password_view.dart';
import 'package:mynotes/views/login_view.dart';
import 'package:mynotes/views/notes/create_update_note_view.dart';
import 'package:mynotes/views/main_ui.dart';
import 'package:mynotes/views/register_view.dart';
import 'package:mynotes/views/settings_view.dart';
import 'package:mynotes/views/verify_email_view.dart';
import "dart:developer" as devtools show log;
const double sizedBoxWidth = 300;
const double sizedBoxHeight = 300;
late Color textColor;
// const Color themeColor = Color.fromRGBO(85, 111, 68, 1);
const Color bgColor = Color.fromRGBO(20, 20, 20, 1);
const Color themeColor = Color.fromARGB(255, 107, 65, 114);
//const Color bgColor = Color.fromARGB(255, 31, 31, 31);
late ThemeData currentTheme;
const Color defTextColor = Colors.white;
dynamic loadingCircle;
late Icon shareIcon;
//Creates an empty sized box for sapce
SizedBox createSpace(double height) {
return SizedBox(height: height);
}
SizedBox createSpaceWidth(double height, double width) {
return SizedBox(
height: height,
width: width,
);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Hive.initFlutter();
Hive.registerAdapter(UserSettingsAdapter());
await Hive.openBox<UserSettings>("user_settings");
//Allows for app restart for themes
runApp(Phoenix(child: const HomePage()));
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
final box = Boxes.getUserSettings();
//Making sure a first time user has the theme setting
if (box.containsKey("defaultKey")) {
if (box.get("defaultKey", defaultValue: UserSettings("Purple"))!.theme ==
"Green") {
currentTheme = MyThemes.greenTheme;
textColor = Colors.white;
} else if (box.get("defaultKey")!.theme == "White") {
currentTheme = MyThemes.lightTheme;
textColor = Colors.black;
} else {
currentTheme = MyThemes.purpleTheme;
textColor = Colors.white;
}
} else {
box.put("defaultKey", UserSettings("Purple"));
currentTheme = MyThemes.purpleTheme;
textColor = Colors.white;
}
return MaterialApp(
title: 'Flutter Demo',
theme: currentTheme,
debugShowCheckedModeBanner: false,
home: const Setup(),
routes: {
loginRoute: (context) => const LoginView(),
registerRoute: (context) => const RegisterView(),
notesRoute: (context) => const MainUIView(),
verifyRoute: (context) => const VerifyEmailView(),
createOrUpdateNoteRoute: (context) => const CreateUpdateNoteView(),
forgotPasswordViewRoute: (context) => const ForgotPasswordView(),
settingsRoute: (context) => const SettingsView(),
homeRoute: (context) => const HomePage(),
},
);
}
}
class Setup extends StatelessWidget {
const Setup({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: Firebase.initializeApp(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
final user = FirebaseAuth.instance.currentUser;
if (user != null) {
if (user.emailVerified) {
return const MainUIView();
} else {
devtools.log(user.toString());
return const VerifyEmailView();
}
} else {
return const LoginView();
}
default:
if (Platform.isIOS) {
loadingCircle = const CupertinoActivityIndicator();
shareIcon = const Icon(Icons.ios_share);
} else {
loadingCircle = const CircularProgressIndicator();
shareIcon = const Icon(Icons.share);
}
return Scaffold(
body: Center(
child: SizedBox(
width: sizedBoxWidth,
height: sizedBoxHeight,
child: Center(child: loadingCircle),
),
),
);
}
},
);
}
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
//initialize it here
await Firebase.initializeApp(),
await Hive.initFlutter();
Hive.registerAdapter(UserSettingsAdapter());
await Hive.openBox<UserSettings>("user_settings");
//Allows for app restart for themes
runApp(Phoenix(child: const HomePage()));
}
static Future<FirebaseApp?> initialize() async {
await Firebase.initializeApp(
options: kIsWeb
? const FirebaseOptions(
appId: appId,
authDomain: authDomain,
apiKey: apiKey,
databaseURL: databaseURL,
projectId: projectId,
storageBucket: storageBucket,
messagingSenderId: messagingSenderId,
measurementId: measurementId,
)
: null);
return Firebase.app();
}
call it.
main() async{
await ClassName.initialize();
}
I am using it like that and it works fine.
Deleted and re-downloaded my project from Github, which fixed the issue.

FLUTTER ERROR: Unhandled Exception: 'package:flutter_downloader/src/downloader.dart'

I've a flutter program which downloads a file by using a URL using the flutter_downloader package.I hace a button where on click will download the file.
Below is my implementation
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await FlutterDownloader.initialize(
debug: true
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page',key: GlobalKey(),),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({required Key key, required this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(height: 60,),
FlatButton(
child: Text("Start Downloading"),
color: Colors.redAccent,
textColor: Colors.white,
onPressed: () async {
final status = await Permission.storage.request();
if (status.isGranted) {
final externalDir = await getExternalStorageDirectory();
final id = await FlutterDownloader.enqueue(
url: "https://firebasestorage.googleapis.com/v0/b/storage-3cff8.appspot.com/o/2020-05-29%2007-18-34.mp4?alt=media&token=841fffde-2b83-430c-87c3-2d2fd658fd41",
savedDir: externalDir!.path,
fileName: "download",
showNotification: true,
openFileFromNotification: true,
);
} else {
print("Permission deined");
}
},
)
],
),
),
);
}
}
The error massage I get when the button is pressed is,
E/flutter (21960): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception:
'package:flutter_downloader/src/downloader.dart': Failed assertion: line 80 pos 12:
'_initialized': FlutterDownloader.initialize() must be called first
E/flutter (21960): #0 _AssertionError._doThrowNew (dart:core-
patch/errors_patch.dart:46:39)
E/flutter (21960): #1 _AssertionError._throwNew (dart:core-
patch/errors_patch.dart:36:5)
E/flutter (21960): #2 FlutterDownloader.enqueue
(package:flutter_downloader/src/downloader.dart:80:12)
E/flutter (21960): #3 _MyHomePageState.build.<anonymous closure>
(package:care_giver_app/functions_test.dart:102:54)
E/flutter (21960): <asynchronous suspension>
E/flutter (21960):
If im not wrong,it states that I have to initialize flutter_downloader first but I've already done that in line No.06-No.09 in the implementation above.
I've provided the necessary providers in the AndroidManifest file as well
<provider
android:name="vn.hunghd.flutterdownloader.DownloadedFileProvider"
android:authorities="${applicationId}.flutter_downloader.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
android:exported="false"
tools:node="merge">
<meta-data
android:name="androidx.work.WorkManagerInitializer"
android:value="androidx.startup"
tools:node="remove" />
</provider>
<!-- declare customized Initializer -->
<provider
android:name="vn.hunghd.flutterdownloader.FlutterDownloaderInitializer"
android:authorities="${applicationId}.flutter-downloader-init"
android:exported="false">
<!-- changes this number to configure the maximum number of concurrent tasks -->
<meta-data
android:name="vn.hunghd.flutterdownloader.MAX_CONCURRENT_TASKS"
android:value="5" />
</provider>

When Using "BlocBuilder" in "MultiBlocProvider" I have get error

I am new in flutter .I am tried googling but I cant fix my problem. I used "MultiBlocProvider" for manage stats . I want change dark mode state like bellow.
ThemeCubit.dart
part 'theme_state.dart';
class ThemeCubit extends HydratedCubit<ThemeState> {
ThemeCubit() : super(ThemeState(AppThemes.lightTheme));
void getTheme(ThemeState state) {
emit(state);
}
#override
ThemeState? fromJson(Map<String, dynamic> json) {
return json['isDark'] as bool
? ThemeState(AppThemes.darkTheme)
: ThemeState(AppThemes.lightTheme);
}
#override
Map<String, bool>? toJson(ThemeState state) {
return {'isDark': state.themeData.brightness == Brightness.dark};
}
}
ThemeState.dart
part of 'theme_cubit.dart';
#immutable
class ThemeState extends Equatable {
final ThemeData themeData;
const ThemeState(this.themeData);
#override
List<Object?> get props => [themeData];
}
main.dart
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(
lazy: true,
create: (context) => ThemeCubit(),
),
],
child:BlocBuilder<ThemeCubit, ThemeState>(
builder: (context,state) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Production Boilerplate',
theme: state.themeData, //ThemeMode.dark,
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
},
),
);
}
}
settingScreen.dart
Positioned(
top: 60 - widget.offset / 2,
left: 20,
child: Builder(builder: (context) {
return Switch(
value:newValue ,
onChanged: (value) {
BlocProvider.of<ThemeCubit>(context).getTheme(ThemeState(
newValue ? AppThemes.darkTheme : AppThemes.lightTheme));
});
})
),
This code works properly when used "BlocProvider" . But when I used "MultiBlocProvider", I get bellow error.
The following assertion was thrown attaching to the render tree:
'package:flutter/src/widgets/framework.dart': Failed assertion: line
4357 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
Either the assertion indicates an error in the framework itself, or we
should provide substantially more information in this error message to
help you determine and fix the underlying cause. In either case,
please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=2_bug.md
When the exception was thrown, this was the stack:
#2 Element.rebuild. (package:flutter/src/widgets/framework.dart:4357:14)
#3 Element.rebuild (package:flutter/src/widgets/framework.dart:4360:6)
#4 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4643:5)
#5 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4638:5)
#6 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3673:14)
#7 Element.updateChild (package:flutter/src/widgets/framework.dart:3425:18)
#8 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1198:16)
#9 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1167:5)
#10 RenderObjectToWidgetAdapter.attachToRenderTree. (package:flutter/src/widgets/binding.dart:1112:18)
#11 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2573:19)
#12 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1111:13)
#13 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:944:7)
#14 WidgetsBinding.scheduleAttachRootWidget. (package:flutter/src/widgets/binding.dart:924:7) (elided 13 frames
from class _AssertionError, class _RawReceivePortImpl, class _Timer,
dart:async, and dart:async-patch)
How can I fix it?
I added bellow code to ThemeCubit.dart :
bool isDarkMode = false;
ThemeMode currentTheme(){
isDarkMode?_setTheme(ThemeMode.dark) : _setTheme(ThemeMode.light);
return isDarkMode?ThemeMode.dark : ThemeMode.light;
}
void updateTheme(bool isDarkMode) {
this.isDarkMode = isDarkMode;
}
and change main.dart :
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => ThemeCubit(),
),
],
child:ElderlyApp(),
);
}
class ElderlyApp extends StatefulWidget {
const ElderlyApp({Key? key,}) : super(key: key);
#override
_ElderlyAppState createState() => _ElderlyAppState();
}
class _ElderlyAppState extends State<ElderlyApp> with WidgetsBindingObserver {
#override
void initState() {
WidgetsBinding.instance!.addObserver(this);
super.initState();
}
#override
void didChangePlatformBrightness() {
context.read<ThemeCubit>().currentTheme();
super.didChangePlatformBrightness();
}
#override
void dispose() {
WidgetsBinding.instance!.removeObserver(this);
super.dispose();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Production Boilerplate',
theme: AppThemes.lightTheme,
darkTheme: AppThemes.darkTheme,
themeMode: context.select(
(ThemeCubit cubit) => cubit.currentTheme()), //ThemeMode.dark,
debugShowCheckedModeBanner: false,
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
and change code in seetingScreen.dart
Positioned(
top: 60 - widget.offset / 2,
left: 20,
child: Builder(builder: (context) {
bool isDark = context.select((ThemeCubit themeCubit) =>
themeCubit.state.themeMode) ==ThemeMode.dark ? true: false;
return Switch(
value: context.read<ThemeCubit>().isDarkMode,
onChanged: (value) {
context.read<ThemeCubit>().updateTheme(value);
});
})),

How to read file txt from storage (Flutter)?

I want to read a config file from a folder on my phone. But I manage to read a part of file and I want to be able to read the entire file. Any Ideas about how to do it the right way?
Here is my code :
import 'dart:io';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:ext_storage/ext_storage.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
// String _platformVersion = 'Unknown';
String _configFile = 'No Data';
static Future<String> get _getPath async {
final localPath = await ExtStorage.getExternalStoragePublicDirectory(
ExtStorage.DIRECTORY_DOWNLOADS);
return localPath;
}
static Future<File> get _localFile async {
final path = await _getPath;
return File('$path/config_test.txt');
}
static Future<String> readConfig() async {
try {
final file = await _localFile;
// Read the file.
String contents = await file.readAsString();
return contents;
} catch (e) {
// If encountering an error, return 0.
return "error";
}
}
#override
void initState() {
super.initState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
if (await FlutterOpenvpn.init(
localizedDescription: "ExampleVPN",
providerBundleIdentifier:
"com.topfreelancerdeveloper.flutterOpenvpnExample.RunnerExtension",
)) {
await FlutterOpenvpn.lunchVpn(
_configFile,
(isProfileLoaded) => print('isProfileLoaded : $isProfileLoaded'),
(vpnActivated) => print('vpnActivated : $vpnActivated'),
//expireAt: DateTime.now().add(Duration(seconds: 30)),
);
}
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('OpenVPN connect Test'),
),
body: Center(
child: Column(
children: <Widget>[
IconButton(
iconSize: 48.0,
splashColor: Colors.greenAccent,
onPressed: _startBtnVpn,
icon: Icon(Icons.play_arrow)),
IconButton(
iconSize: 48.0,
splashColor: Colors.greenAccent,
icon: Icon(Icons.stop),
onPressed: _stopBtnVPN,
),
IconButton(
iconSize: 48.0,
splashColor: Colors.greenAccent,
icon: Icon(Icons.cloud),
onPressed: () {
readConfig().then((value) {
setState(() {
_configFile = value;
print(_configFile);
});
});
}),
],
),
),
),
);
}
void _startBtnVpn() {
setState(() {
initPlatformState();
});
}
void _stopBtnVPN() {
FlutterOpenvpn.stopVPN();
}
}
DEBUG CONSOLE:
I/flutter (17341): "dev tun\n" +
I/flutter (17341): "proto udp\n" +
I/flutter (17341): "remote public-vpn-255.opengw.net 1195\n" +
I/flutter (17341): ";http-proxy-retry\n" +
I/flutter (17341): ";http-proxy [proxy server] [proxy port]\n" +
I/flutter (17341): "cipher AES-128-CBC\n" +
I/flutter (17341): "auth SHA1\n" +
I/flutter (17341): "resolv-retry infinite\n" +
I/flutter (17341): "nobind\n" +
I/flutter (17341): "persist-key\n" +
I/flutter (17341): "persist-tun\n" +
I/flutter (17341): "client\n" +
I/flutter (17341): "verb 3\n" +
I/flutter (17341): "<ca>\n" +
I/flutter (17341): "-----BEGIN CERTIFICATE-----\n" +
I/flutter (17341): "MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB\n" +
I/flutter (17341): "iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl\n" +
I/flutter (17341): "cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV\n" +
I/flutter (17341): "BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw\n" +
I/flutter (17341): "MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV\n" +
I/flutter (17341): "BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU\n" +
I/flutter (17341): "aGUgVVNFUlR
The problem is that the print function has a limitation for printing outputs to the console, and it doesn't print long strings completely. Try setting a break point using your IDE or editor and check out the value read from the file.