Home > Blockchain >  Make a button asynchronous in Dart
Make a button asynchronous in Dart

Time:06-28

I have to put this two "on tap" functions in only one button. The thing is that I only can execute the Navigator.push after saveQuestionModel() and loadQuestions() have been already executed.

 onTap: () {
    saveQuestionModel(_key, snapshot.data);
    loadQuestions(_key);
 },

 onTap: () {
    Navigator.push(
     context,
     MaterialPageRoute(
        builder: (context) => QuizScreen(
           code: _key,
           index: _currentIndex,
        ),
     ),
  );

I tried like this but did not work

 onTap: () async {
    saveQuestionModel(_key, snapshot.data);
    loadQuestions(_key);
    await Navigator.push(
       context,
       MaterialPageRoute(
         builder: (context) => QuizScreen(
           code: _key,
           index: _currentIndex,
         ),
      ),
    );
  },

Is there a way of doing that without using two separated buttons?

CodePudding user response:

Create a separate method that will hold all your methods and use await before future methods.

void myFun() async{
   
   await myFutureLoad();   
   // include others
   ....

}

And use this myFun on widget onTap

onTap: myFun,

For your case, you can do

 onTap: () async{
    await saveQuestionModel(_key, snapshot.data);
    await loadQuestions(_key);
     Navigator.push(
     context,
     MaterialPageRoute(
        builder: (context) => QuizScreen(
           code: _key,
           index: _currentIndex,
        ),
     ),
  );
 },

More about dart async-await

CodePudding user response:

In your case, it should be

onTap:()async{
  await saveQuestionModel();
  await loadQuestions();
  
  Navigator.push(...)
}

Here basically it waits for both the functions to end executing before pushing the next page using Navigator.push()

  • Related