简体   繁体   English

在 Dart 中使按钮异步

[英]Make a button asynchronous in Dart

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.问题是我只能在saveQuestionModel()loadQuestions()已经执行之后才能执行Navigator.push

 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?有没有办法在不使用两个分开的按钮的情况下做到这一点?

Create a separate method that will hold all your methods and use await before future methods.创建一个单独的方法来保存您的所有方法并在将来的方法之前使用await

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

}

And use this myFun on widget onTap并在小部件onTap上使用这个myFun

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更多关于飞镖异步等待

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()基本上,它在使用Navigator.push()推送下一页之前等待两个函数结束执行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM