How to read file txt from storage (Flutter)? - 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.

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.

Flutter/dart:: Adding a new field to class causing an error

I added a new field to the class CloudNote, now I am getting an error!
I am getting the error when the app is trying to display a list.
Here is all my code without adding the field :: https://github.com/casas1010/flutter_firebase_vendor_management
I know its a simple issue, but I have tried to troubleshoot this for like an hour and have not made any progress
CloudNote class::
import 'package:cloud_firestore/cloud_firestore.dart';
import '/services/cloud/cloud_storage_constants.dart';
import 'package:flutter/foundation.dart';
/*
https://youtu.be/VPvVD8t02U8?t=87934
*/
#immutable
class CloudNote {
final String documentId;
final String jobCreatorId;
final String jobDescription;
final String jobState; // I added this
const CloudNote({
required this.documentId,
required this.jobCreatorId,
required this.jobDescription,
required this.jobState, // I added this
});
// acts as constructor
CloudNote.fromSnapshot(QueryDocumentSnapshot<Map<String, dynamic>> snapshot)
: documentId = snapshot.id,
jobCreatorId = snapshot.data()[jobCreatorIdColumn],
jobState = snapshot.data()[jobStateColumn], // I added this
jobDescription = snapshot.data()[jobDescriptionColumn] as String;
}
notes view ::
import 'package:flutter/material.dart';
import '/constants/routes.dart';
import '/enums/menu_action.dart';
import '/services/auth/auth_service.dart';
import '/services/cloud/cloud_note.dart';
import '/services/cloud/firebase_cloud_storage.dart';
import '/utilities/dialogs/logout_dialog.dart';
import '/views/notes/notes_list_view.dart';
class NotesView extends StatefulWidget {
const NotesView({Key? key}) : super(key: key);
#override
_NotesViewState createState() => _NotesViewState();
}
class _NotesViewState extends State<NotesView> {
late final FirebaseCloudStorage _notesService;
String get userId => AuthService.firebase().currentUser!.id;
#override
void initState() {
_notesService = FirebaseCloudStorage();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Your jobs'),
actions: [
IconButton(
onPressed: () {
Navigator.of(context).pushNamed(createOrUpdateNoteRoute);
},
icon: const Icon(Icons.add),
),
PopupMenuButton<MenuAction>(
onSelected: (value) async {
switch (value) {
case MenuAction.logout:
final shouldLogout = await showLogOutDialog(context);
if (shouldLogout) {
await AuthService.firebase().logOut();
Navigator.of(context).pushNamedAndRemoveUntil(
loginRoute,
(_) => false,
);
}
}
},
itemBuilder: (context) {
return const [
PopupMenuItem<MenuAction>(
value: MenuAction.logout,
child: Text('Log out'),
),
];
},
)
],
),
body: StreamBuilder(
stream: _notesService.allNotes(jobCreatorId: userId),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
case ConnectionState.active:
if (snapshot.hasData) {
final allNotes = snapshot.data as Iterable<CloudNote>;
return NotesListView(
notes: allNotes,
onDeleteNote: (note) async {
await _notesService.deleteNote(documentId: note.documentId);
},
onTap: (note) {
Navigator.of(context).pushNamed(
createOrUpdateNoteRoute,
arguments: note,
);
},
);
} else {
return const CircularProgressIndicator();
}
default:
return const CircularProgressIndicator();
}
},
),
);
}
}
Error
The following _TypeError was thrown building NotesListView(dirty):
type 'Null' is not a subtype of type 'String'
The relevant error-causing widget was
NotesListView
lib/…/notes/notes_view.dart:72
When the exception was thrown, this was the stack
#0 new CloudNote.fromSnapshot
package:ijob_clone_app/…/cloud/cloud_note.dart:26
#1 FirebaseCloudStorage.allNotes.<anonymous closure>.<anonymous closure>
package:ijob_clone_app/…/cloud/firebase_cloud_storage.dart:39
#2 MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31)
#3 ListIterator.moveNext (dart:_internal/iterable.dart:342:26)
#4 WhereIterator.moveNext (dart:_internal/iterable.dart:438:22)
#5 Iterable.length (dart:core/iterable.dart:497:15)
#6 NotesListView.build
package:ijob_clone_app/…/notes/notes_list_view.dart:26
#7 StatelessElement.build
package:flutter/…/widgets/framework.dart:4949
#8 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4878
#9 Element.rebuild
package:flutter/…/widgets/framework.dart:4604
#10 ComponentElement._firstBuild
package:flutter/…/widgets/framework.dart:4859
#11 ComponentElement.mount
package:flutter/…/widgets/framework.dart:4853
#12 Element.inflateWidget
package:flutter/…/widgets/framework.dart:3863
#13 Element.updateChild
package:flutter/…/widgets/framework.dart:3586
#14 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4904
#15 StatefulElement.performRebuild
package:flutter/…/widgets/framework.dart:5050
#16 Element.rebuild
package:flutter/…/widgets/framework.dart:4604
#17 BuildOwner.buildScope
package:flutter/…/widgets/framework.dart:2667
#18 WidgetsBinding.drawFrame
package:flutter/…/widgets/binding.dart:882
#19 RendererBinding._handlePersistentFrameCallback
package:flutter/…/rendering/binding.dart:378
#20 SchedulerBinding._invokeFrameCallback
package:flutter/…/scheduler/binding.dart:1175
#21 SchedulerBinding.handleDrawFrame
package:flutter/…/scheduler/binding.dart:1104
#22 SchedulerBinding._handleDrawFrame
package:flutter/…/scheduler/binding.dart:1015
#23 _invoke (dart:ui/hooks.dart:148:13)
#24 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:318:5)
#25 _drawFrame (dart:ui/hooks.dart:115:31)
════════════════════════════════════════════════════════════════════════════════
NotesListView ::
import 'package:flutter/material.dart';
import '/services/cloud/cloud_note.dart';
import '/utilities/dialogs/delete_dialog.dart';
/*
source: https://www.youtube.com/watch?v=VPvVD8t02U8&t=59608s
class creation :: 22:02:54
*/
typedef NoteCallback = void Function(CloudNote note);
class NotesListView extends StatelessWidget {
final Iterable<CloudNote> notes; // list of notes
final NoteCallback onDeleteNote;
final NoteCallback onTap;
const NotesListView({
Key? key,
required this.notes,
required this.onDeleteNote,
required this.onTap,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: notes.length,
itemBuilder: (context, index) {
final note =
notes.elementAt(index); // current note whose data we are returning
return ListTile(
onTap: () {
onTap(note);
},
title: Text(
note.jobDescription,
maxLines: 1,
softWrap: true,
overflow: TextOverflow.ellipsis,
),
trailing: IconButton(
onPressed: () async {
final shouldDelete = await showDeleteDialog(context);
if (shouldDelete) {
onDeleteNote(note);
}
},
icon: const Icon(Icons.delete),
),
);
},
);
}
}
This happens if you forget to update your Firestore entries. Atleast one of your CloudNote entries in Firestore does not have the field jobState. That's why Firestore returns a Null value. But it tries to map to String which leads to an exception.
Make sure to rerun the project.
or
flutter clean
and then
flutter run

SQFLite DataBase Not Created

I have tried everything I know But Not been able to solve the issue
RUN Output :
Launching lib\main.dart on moto g 40 fusion in debug mode...
Running Gradle task 'assembleDebug'...
√ Built build\app\outputs\flutter-apk\app-debug.apk.
D/FlutterLocationService(30742): Creating service.
D/FlutterLocationService(30742): Binding to location service.
Debug service listening on ws://127.0.0.1:51746/KGrWp8utBGI=/ws
Syncing files to device moto g 40 fusion...
E/SQLiteLog(30742): (1) no such table: placestore in "SELECT * FROM placestore"
I/AssistStructure(30742): Flattened final assist data: 396 bytes, containing 1 windows, 3 views
D/MediaScannerConnection(30742): Scanned /data/user/0/com.example.memory_place/cache/04c048c7-d58f-497c-b050-fb56e943fc1b615751689670497232.mp4 to null
D/ThumbnailPlugin(30742): original w:1080, h:1920 => 150, 267
E/flutter (30742): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: FileSystemException: Cannot copy file to '/data/user/0/com.example.memory_place/app_flutter/�$��� 5�5f��O ���
======== Exception caught by gesture ===============================================================
The following LateError was thrown while handling a gesture:
LateInitializationError: Field '_CurrentThumbnail#643317077' has not been initialized.
When the exception was thrown, this was the stack:
#0 AddScreen._CurrentThumbnail (package:memory_place/Screens/add_places_screen.dart)
#1 AddScreen.build.SafePlace (package:memory_place/Screens/add_places_screen.dart:25:47)
#2 AddScreen.build. (package:memory_place/Screens/add_places_screen.dart:64:15)
#3 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
#4 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:198:24)
#5 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:608:11)
#6 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
#7 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:230:7)
#8 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:563:9)
#9 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:94:12)
#10 PointerRouter._dispatchEventToRoutes. (package:flutter/src/gestures/pointer_router.dart:139:9)
#11 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8)
#12 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:137:18)
#13 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:123:7)
#14 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:439:19)
#15 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
#16 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:322:11)
#17 GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
#18 GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
#19 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
#20 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
#24 _invoke1 (dart:ui/hooks.dart:170:10)
#25 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:331:7)
#26 _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
(elided 3 frames from dart:async)
Handler: "onTap"
Recognizer: TapGestureRecognizer#12cd2
debugOwner: GestureDetector
state: possible
won arena
finalPosition: Offset(239.2, 911.2)
finalLocalPosition: Offset(239.2, 11.2)
button: 1
sent tap down
DB HELPER FILE:
import 'package:sqflite/sqflite.dart' as sql;
import 'package:path/path.dart' as p;
class dbHelper{
static Future<sql.Database> DataBase() async{
return sql.openDatabase(p.join(await sql.getDatabasesPath(),'memory_place.db'),
onCreate: (db, version) async{
return await db.execute('CREATE TABLE placestore(id TEXT PRIMARY KEY, title TEXT, video TEXT, thumbnail TEXT)');
},version: 1);
}
static Future<void> insert(String Table,Map<String,Object> data) async{
final db = await dbHelper.DataBase();
db.insert(
Table,
data,
conflictAlgorithm: sql.ConflictAlgorithm.replace);
}
static Future<List<Map<String,dynamic>>> getData(String table) async{
final db = await dbHelper.DataBase();
return db.query(table);
}
}
IMAGE INPUT PAGE :
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart' as syspath;
import 'package:path/path.dart' as p;
import 'package:video_thumbnail/video_thumbnail.dart';
class ImageInput extends StatefulWidget {
Function onSelected;
ImageInput({required this.onSelected});
#override
State<ImageInput> createState() => _ImageInputState();
}
class _ImageInputState extends State<ImageInput> {
XFile ? _referenceXFileVid;
File? _referenceVidFile;
Future<void> TakePic() async{
final _imagePicker = ImagePicker();
final NewFile = await _imagePicker.pickVideo(
source: ImageSource.camera,
maxDuration: Duration(minutes: 1));
setState(() {
_referenceVidFile = File(NewFile!.path);
_referenceXFileVid = NewFile;
});
}
Future<Uint8List?> VideoThumbNail(XFile Video) async{
final uint8list = await VideoThumbnail.thumbnailData(
video: Video.path,
imageFormat: ImageFormat.JPEG,
maxWidth: 150,
quality: 25,
);
return await uint8list;
}
#override
Widget build(BuildContext context) {
return Row(
children: [
Container(
height: 267,
width: 150,
alignment: Alignment.center,
decoration: BoxDecoration(
border: Border.all(width: 1,color: Colors.grey),
),
child: _referenceVidFile!= null ?
FutureBuilder<Uint8List?>(
future: VideoThumbNail(_referenceXFileVid!),
builder: (context,uint8) {
if(uint8.hasData){
final ImagePath = uint8.data;
final CurrentThumbImg = Image.memory(ImagePath!,
height: 267,
width: 150,
fit: BoxFit.cover,);
SaveVidAndThumb(_referenceVidFile!,File.fromRawPath(ImagePath));
return CurrentThumbImg;
}else{
return Center(child: Text('Saumya Made Mistake',textAlign: TextAlign.center,));
}
}) : Text('No Video Taken',textAlign: TextAlign.center,),
),
SizedBox(width: 10,),
Expanded(
child: FlatButton.icon(onPressed: (){
TakePic();
},
icon: Icon(Icons.camera),
label: Text('Take Video'),
textColor: Theme.of(context).primaryColor,),
),
],
);
}
void SaveVidAndThumb(File Video,File Thumbnail) async{
final appDir = await syspath.getApplicationDocumentsDirectory();
final VideoPath = p.basename(Video.path);
final ThumbPath = p.basename(Thumbnail.path);
final Savedvideo = await Video.copy('${appDir.path}/$VideoPath');
final SavedThumb = await Thumbnail.copy('${appDir.path}/$ThumbPath');
widget.onSelected(Savedvideo,SavedThumb);
}
}
ADD PLACES SCREEN :
import 'dart:io';
import 'package:memory_place/models/Video_format.dart';
import 'package:memory_place/providers/place_provider.dart';
import 'package:memory_place/widgets/Location_Input.dart';
import 'package:provider/provider.dart';
import 'package:flutter/material.dart';
import 'package:memory_place/widgets/Image_Input.dart';
class AddScreen extends StatelessWidget {
TextEditingController _TitleTextController = TextEditingController();
late File _CurrentVideo;
late File _CurrentThumbnail;
void CallCurrentImage(File CurrentVideo,File CurrentThumbnail){
if(CurrentVideo!=null){
_CurrentVideo = CurrentVideo;
_CurrentThumbnail = CurrentThumbnail;
}
}
#override
Widget build(BuildContext context) {
void SafePlace(){
if(_TitleTextController.text == null || _CurrentThumbnail == null){
throw Text('Either Title or Image is Missing');
}else {
Provider.of<PlaceProvider>(context, listen: false).AddPlace(
_TitleTextController.text,
_CurrentVideo,
_CurrentThumbnail);
Navigator.pop(context);
}
}
return Scaffold(
appBar: AppBar(
title: Text('Add Place Screen'),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child:SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(10.0),
child: Column(
children: [
TextField(
decoration: InputDecoration(label: Text('Title...')),
controller: _TitleTextController,
),
SizedBox(height: 20,),
ImageInput(onSelected: CallCurrentImage),
SizedBox(height: 20,),
LocationInput(),
],
),
),
) ),
RaisedButton.icon(
onPressed: (){
SafePlace();
},
icon: Icon(Icons.add),
label: Text('Add Place'),
elevation: 0,
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
color: Theme.of(context).accentColor,
)
],
),
);
}
}
When you declare a variable as late , you are actually indicating that it won't be null.
In your code, you're declaring_CurrentThumbnail variable as late but not
instantiating it.
You can change your AddScreen widget to StatefulWidget and instantiate _CurrentThumbnail inside initState function.(or even call CallCurrentImage inside initState)

How do you use the flutter/dart package spreadsheet_decoder?

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();

How infinite scroll Flutter over REST pagination with provider?

I created a flutter project with provider package
Previously it had run well using ScopedModel following this sample project.
I want to implement v3 provider with the same logic,
// main.dart
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(builder: (context) => NoteContentModel()),
],
...
home: NoteContentPage(),
),
);
}
// note_content_model.dart
class NoteContentModel extends ChangeNotifier {
final _pageSize = 30;
List<Content> _content = [];
bool _isLoading = false;
int _totalResults;
int _totalPages;
bool _hasMorePages = true;
String _placeName;
bool _isLoadingMore = false;
// .. other setter getter
int getNoteCount() => _content.length;
Future<dynamic> _getData([int page = 1]) async {
var res = await http.get(getUrl(page));
return jsonDecode(res.body);
}
Future getNoteContent([int page = 1]) async {
if (page == 1) {
_isLoading = true;
_content.clear();
} else {
_isLoadingMore = true;
}
notifyListeners();
var responseData = await _getData();
List noteContent = responseData['content'];
noteContent.forEach((content) {
_content.add(Content.fromJson(content));
});
_totalResults = responseData['total_count'];
_totalPages = responseData['page_count'];
if (responseData['page_number'] == totalPages) {
_hasMorePages = false;
}
if (page == 1) {
_isLoading = false;
} else {
_isLoadingMore = false;
}
notifyListeners();
}
}
// note_content_page.dart
class NoteContentPage extends StatefulWidget {
#override
_NoteContentPageState createState() => _NoteContentPageState();
}
class _NoteContentPageState extends State<NoteContentPage> {
int page = 1;
ScrollController controller;
void _scrollListener() {
final NoteContentModel noteModel = Provider.of<NoteContentModel>(context);
if (controller.position.pixels == controller.position.maxScrollExtent) {
if (!noteModel.isLoadingMore && noteModel.hasMorePages) {
page++;
print("Current page: $page");
noteModel.getNoteContent(page);
}
}
}
#override
void initState() {
super.initState();
controller = new ScrollController()..addListener(_scrollListener);
}
#override
void dispose() {
super.dispose();
controller.dispose();
}
#override
Widget build(BuildContext context) {
final NoteContentModel noteModel = Provider.of<NoteContentModel>(context);
// Call initiate first page
noteModel.getNoteContent(page);
return Scaffold(
appBar: AppBar(title: Text("Test")),
body: CustomScrollView(
controller: controller,
slivers: <Widget>[
noteModel.isLoading
? SliverFillRemaining(
child: Center(
child: CircularProgressIndicator(),
),
)
: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
if (index == noteModel.getNoteCount()) {
if (noteModel.hasMorePages) {
print("here1");
return Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: Center(child: CircularProgressIndicator()),
);
}
return Container();
} else {
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(noteModel.content[index].title),
// child: Text("test"),
),
],
);
}
},
childCount: noteModel.getNoteCount(),
),
)
],
),
);
}
}
I always got this message loop markNeedsBuild() called during build end trace error
I/flutter ( 2525): ══╡ EXCEPTION CAUGHT BY FOUNDATION LIBRARY ╞════════════════════════════════════════════════════════
I/flutter ( 2525): The following assertion was thrown while dispatching notifications for NoteContentModel:
I/flutter ( 2525): setState() or markNeedsBuild() called during build.
I/flutter ( 2525): This ListenableProvider<NoteContentModel> widget cannot be marked as needing to build because the
...
I/flutter ( 2525): #0 Element.markNeedsBuild.<anonymous closure> (package:flutter/src/widgets/framework.dart:3670:11)
I/flutter ( 2525): #1 Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:3685:6)
I/flutter ( 2525): #2 State.setState (package:flutter/src/widgets/framework.dart:1161:14)
I/flutter ( 2525): #3 __BuilderListenableDelegate&BuilderStateDelegate&_ListenableDelegateMixin.startListening.<anonymous closure> (package:provider/src/listenable_provider.dart:186:36)
I/flutter ( 2525): #4 ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:206:21)
I/flutter ( 2525): #5 NoteContentModel.getNoteContent (package:paging_provider/providers/note_content_model.dart:42:5)
I/flutter ( 2525): <asynchronous suspension>
I/flutter ( 2525): #6 _NoteContentPageState.build (package:paging_provider/pages/note_content_page.dart:44:15)
I/flutter ( 2525): #7 StatefulElement.build (package:flutter/src/widgets/framework.dart:4012:27)
I/flutter ( 2525): #8 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3924:15)
I/flutter ( 2525): #9 Element.rebuild (package:flutter/src/widgets/framework.dart:3721:5)
I/flutter ( 2525): #10 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3907:5)
...
// This trace always loop on app running
I/flutter ( 2525): Another exception was thrown: setState() or markNeedsBuild() called during build....
so that's all, any response will be appreciated.
You must wrap your functions in addPostFrameCallback():
So the call is submitted after the build function finish it work and draw widgets over screen
//Change
noteModel.getNoteContent(page);
//To
WidgetsBinding.instance.addPostFrameCallback((_) => noteModel.getNoteContent(page);
);
Hope this answer being valuable for someone.