Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

fetching data from file and to show on screen failing in flutter

I have a screen of restoring data from json file….here i want to show all data which are taken back up for restoring….

List<Note> restoreNotes=[];
  Future<void> fetchNotes() async {
    String path =
        '/storage/emulated/0/Android/data/com.example.noteapp/backup_data2.json';
    File? file = File(path);
    bool doesFileExists = await file.exists();
    if(doesFileExists==true) {
      if (await File(path).length() != 0) {
        //append data
        List<dynamic> list = jsonDecode(await file.readAsString());
        for (var i = 0; i < list.length; i++) {
          Note note = Note.fromJson(list[i] as Map<String, dynamic>);
          restoreNotes.add(note);
        }
      }
    }

  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    fetchNotes();
  }

its working but i have to press refresh button for set state

later i will user ListView.builder to show this fetched data….

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

is it possible without using future.builder?

>Solution :

Yes, it is possible!! you can manually trigger a UI update by calling setState after the data is fetched

You need to use:

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      fetchNotes().then((_) {
        setState(() {
            // Call setState after fetching data to trigger the UI update
         });
     });
   }

Then you need a ListView.builder to show that on Screen.

Here is an example code:

@override
  Widget build(BuildContext context) {
    // Your UI with ListView.builder using restoreNotes data
    return Scaffold(
      // Your Scaffold content here
      body: ListView.builder(
        itemCount: restoreNotes.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(restoreNotes[index].title),
            // Other ListTile content here
          );
        },
      ),
    );
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading