首页 > 解决方案 > 按下按钮时未显示警报对话框

问题描述

警报对话框类

class AlertWindow extends StatelessWidget {
  final String title;

  const AlertWindow({Key key, this.title}) : super(key: key);


  @override
  Widget build(BuildContext context) {

    return Builder(
        builder:(BuildContext context) {
          return AlertDialog(
            title: Text(this.title),
            actions: <Widget>[
              new FlatButton(
                  onPressed: (){
                    Navigator.of(context).pop();
                  },
                  child: new Text(
                      "OK"
                  )
              ),
            ],
          );
        }
    );
  }
}

它在这样的aysnc函数中被调用

  Future<ParseUser> SignUP(username, pass, email) async {
    var user = ParseUser(username, pass, email);   // You can add columns to user object adding "..set(key,value)"
    var result = await user.create();
    if (result.success) {
      setState(() {
        _parseUser = user;     // Keep the user
      });
      print(user.objectId);
      new AlertWindow(
        title: "Signup success " + user.objectId,
      );
    } else {
      print(result.error.message);
      new AlertWindow(
        title: "Signup error " + result.error.message,
      );
    }
  }

在运行它时,我可以print在控制台中看到语句,但AlertWindow没有出现。

我有一种预感,它可能与我创建它时BuildContext没有传递给父级有关。AlertDialog

标签: flutterdart

解决方案


您需要调用该函数showDialog才能AlertDialog出现:

class AlertWindow  {
  final String title;
  final BuildContext context;

  const AlertWindow({Key key, this.title, this.context});

  void widget(){
           showDialog(
          context: context,
          builder: (BuildContext context) {
          return AlertDialog(
            title: Text(this.title),
            actions: <Widget>[
              new FlatButton(
                  onPressed: (){
                    Navigator.of(context).pop();
                  },
                  child: new Text(
                      "OK"
                  )
              ),
            ],
          );
        }
    );
  }

  }

工作示例:

https://dartpad.dev/051f787e1737de84609a390d31c36ee0

https://api.flutter.dev/flutter/material/showDialog.html


推荐阅读