Search code examples
flutterdartsetstate

setState method works sometimes and sometimes doesn't in flutter


I'm trying to navigate between the loading screen and the main app screen using the inline if in the body parameter of the Scaffold object of the main Screen , using the code :

body : data == null?
Center(
  child: CircularProgressIndicator(),
)
:(
data1 == null?
Center(
  child: CircularProgressIndicator(),
)
:Center(child: Text('Data imported successfully'),)
),

Note : the data1 is delayed with 10 sec from the data.

so I needed a setState so when the two conditions have false value the Data imported successfully text appears in the middle of the screen , I'm importing the data and the data1 in the initState of the main screen with the code :

void initState() {
    // TODO: implement initState
    super.initState();
    createDatabase()
        .then((value){
          getDataFromDatabase().then((value){setState(() {});});
        });
    createDatabase1()
        .then((value){
          getDataFromDatabase1().then((value){setState(() {});});
    });
  }

sometimes the code work properly and sometimes doesn't

I wonder why this is happening and how can I solve it ?

Thank you very much!


Solution

  • Check below code that reduce your line of code as well as rebuild of flutter page

    void initState() {
            // TODO: implement initState
            super.initState();
            Future.delayed(Duration.zero,(){
              _createDatabaseFunc();
            });
          }
        
          Future<void> _createDatabaseFunc() async {
            var firstDB = await createDatabase();
            var data = await getDataFromDatabase();
            var firstDB1 = await createDatabase1();
            var data1 = await getDataFromDatabase1();
            setState(() {}); // only single time refresh 
          }