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….
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
);
},
),
);
}