skip to Main Content

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!

2

Answers


  1. change you initState to this:

    void initState() {
      super.initState();
      Future.wait([
        createDatabase().then((value) => getDataFromDatabase()),
        createDatabase1().then((value) => getDataFromDatabase1().timeout(Duration(seconds: 10))),
      ]).then((List<dynamic> results) {
        setState(() {
          data = results[0];
          data1 = results[1];
        });
      }).catchError((error) {
        // Handle any errors
      });
    }
    

    I hope I could solve your problem.

    Login or Signup to reply.
  2. 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 
          }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search