0

I am currently developing an sqflite application with flutter and trying to set state of my list after performing a navigator.pop operation from another screen but it doesn't load the new state unless I make a hotrestart.Useful snippets from my code are below.Also, I can share whole code if it helps. How can I set state of listView without restarting my app?

// these methods are on my first screen that I display my listview
void getNoteList() {
    final notesFutureList = db.getNotes();
    notesFutureList.then((data) {
      setState(() {
        notes =  data;
      });
    });

  }

  @override
  void initState() {
    getNoteList();
  }

// This method is on my adding screen attached to the button which performs the saving. 
Future<void> saveNote(BuildContext context) async {
    await db.insertNote(Note(
        header: myControllerHeader.text,
        detail: myControllerDetail.text)); // inserted to db.
    Navigator.pop(context);
   // Navigator.push(context, MaterialPageRoute(builder: (context) => const NoteListScreen(),));
    // if a use another push like this it's working. But doesn't look like a good way.
  }
Furkan
  • 177
  • 9
  • You can try to pass a setstate method but I guess a cleaner solution would be using statemanagement – DEFL Apr 21 '22 at 09:26
  • Already tried setState method. But didn't work out – Furkan Apr 21 '22 at 09:27
  • If you don't wanna go with statemanagament there are several posts that explain how to use setState https://stackoverflow.com/questions/48481590/how-to-set-update-state-of-statefulwidget-from-other-statefulwidget-in-flutter – DEFL Apr 21 '22 at 09:29

1 Answers1

3

You can turn the function into async from where you are saying Navigator.push(). Wait for the return of route and then setState. Just like

navigateToDataEntryScreen()async{
 await Navigator.pushNamed("DataAddingScreen");
 setState((){});
}

Or

navigateToDataEntryScreen()async{
 await Navigator.pushNamed("DataAddingScreen");
 getNoteList();
}
Naveed Ullah
  • 129
  • 7
  • getNoteList() seems to be working out the problem. But could you kindly explain how it happened? So, does navigateToDataEntryScreen() method complete when returning to the main screen, which displays list elements ? – Furkan Apr 21 '22 at 10:04
  • 1
    Sure Furkan. So basically what happened, you went to next screen to add data to database. So you need to reload the data back to memory. We used await keyword, which waits until the screen pops back. Once screen is popped back, the next line is executed. Which is getNoteList() function in this case. This function reloads the data and update the state. Hope answers your question. – Naveed Ullah Apr 21 '22 at 10:06