使用范围模型显示对话框

时间:2019-03-04 12:14:15

标签: flutter scoped-model

我有一个基本的登录表单,上面有我的LoginModel。 但是我不明白如何调用函数notifyListeners在视图中显示对话框。

登录小部件:

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        body: new ScopedModel<LoginModel>(
            model: _loginModel,
            child: Center(child: ScopedModelDescendant<LoginModel>(
                builder: (context, child, model) {
              if (model.status == Status.LOADING) {
                return Loading();
              }
              else return showForm(context);
            }))));
  }

登录模式:

class LoginModel extends Model {

  Status _status = Status.READY;
  Status get status => _status;

  void onLogin(String username, String password) async {
    _status = Status.LOADING;
    notifyListeners();

    try {
      await api.login();
      _status = Status.SUCCESS;
      notifyListeners();

    } catch (response) {
      _status = Status.ERROR;
      notifyListeners();
    }
  }

statusError时,我需要显示一个对话框

1 个答案:

答案 0 :(得分:1)

最后我得到了,只是在方法onLogin中返回了Future。

Future<bool> onLogin(String username, String password) async {
    _status = Status.LOADING;
    notifyListeners();

    try {
      await api.login();
      _status = Status.SUCCESS;
      notifyListeners();
      return true;

    } catch (response) {
      _status = Status.ERROR;
      notifyListeners();
      return false;
    }
}

在小部件中:

onPressed: () async {
     bool success = await _loginModel.onLogin(_usernameController.text, _passwordController.text);
     if(success) {
        Navigator.pop(context, true);
      }
      else{
        _showDialogError();
      }
}
相关问题