Как я могу передать функцию возвращаемого типа Future <Dynamic>без ее выполнения, прежде чем я решу сделать это в дротике - PullRequest
0 голосов
/ 06 августа 2020

Я создал диалоговое окно в своем приложении Flutter и хочу, чтобы его можно было использовать повторно. Поэтому каждый раз, когда я вызываю его, я передаю два аргумента: текст, который будет отображаться пользователю, и функцию, которая будет выполняться, если они подтвердят действие. вот код

Виджет диалога

              child: Column(
                children: <Widget>[
                  Expanded(
                      child: Padding(
                        padding: const EdgeInsets.only(
                            top: 30.0, left: 20.0, right: 20.0),
                        child: Text(

                            //The text argument is passed here

                          widget.text,
                          style: TextStyle(color: Colors.grey[600], fontSize: 16.0),
                        ),
                      )),
                  Expanded(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Padding(
                            padding: const EdgeInsets.all(10.0),
                            child: ButtonTheme(
                                height: 35.0,
                                minWidth: 110.0,
                                child: RaisedButton(
                                  color: Colors.black,
                                  shape: buttonShapeDeco,
                                  splashColor: Colors.black.withAlpha(40),
                                  child: Text(
                                    widget.button,
                                    textAlign: TextAlign.center,
                                    style: TextStyle(
                                        color: Colors.grey,
                                        fontWeight: FontWeight.bold,
                                        fontSize: 13.0),
                                  ),
                                  onPressed: ()async{

                                  //I expect the passed function to be executed here after the user confirms the action
                                    await widget.action;

                                    }
                                  },
                                )),
                          ),
                          Padding(
                              padding: const EdgeInsets.only(
                                  left: 20.0, right: 10.0, top: 10.0, bottom: 10.0),
                              child:  ButtonTheme(
                                  height: 35.0,
                                  minWidth: 110.0,
                                  child: RaisedButton(
                                    color: Colors.black,
                                    shape: buttonShapeDeco,
                                    splashColor: Colors.white.withAlpha(40),
                                    child: Text(
                                      'Cancel',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                          color: Colors.grey,
                                          fontWeight: FontWeight.bold,
                                          fontSize: 13.0),
                                    ),
                                    onPressed: () {
                                      setState(() {
                                      Navigator.pop(context);
                                    });
                                    },
                                  ))
                          ),
                        ],
                      ))
                ],
              )),

В моем случае я пытаюсь выйти из системы только после того, как они нажмут кнопку подтверждения для выхода.

Вот код

                    onTap: ()async{
                      showDialog(
                        context: context,
                        builder: (_) => Dialogue(text: 'Are you sure you want to logout?',button: 'Logout',action: _auth.signOut(),pop:true),
                      );
                      },

Проблема в том, что функция выполняется, как только открывается диалоговое окно, прежде чем пользователь сможет подтвердить действие. Как я могу это обойти?

Ответы [ 2 ]

1 голос
/ 06 августа 2020

изменить действие с _auth.signOut() на ()=>_auth.signOut()

onTap: ()async{
    showDialog(
      context: context,
      builder: (_) => Dialogue(text: 'Are you sure you want to logout?',button: 'Logout',action: ()=>_auth.signOut(),pop:true),
    );
  }
0 голосов
/ 06 августа 2020

В вашем виджете Dialogue вам нужно изменить тип параметра action на Future<dynamic> Function(). А затем передайте ему функцию _auth.signOut.

Виджет диалога

class Dialogue extends StateFulWidget {
  Future<dynamic> Function() action;
  //other code
}

Передайте ему функцию signOut

onTap: ()async{
    showDialog(
      context: context,
      builder: (_) => Dialogue(text: 'Are you sure you want to logout?', button: 'Logout', action: _auth.signOut, pop:true),
    );
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...