一尘不染

在应用程序主屏幕上显示警报对话框会自动在抖动中加载

flutter

我想根据条件显示警报对话框。不基于用户交互,例如按钮按下事件。

如果在应用程序状态数据中设置了标志,则显示警告对话框,否则不显示。

下面是我要显示的示例警报对话框

  void _showDialog() {
    // flutter defined function
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: new Text("Alert Dialog title"),
          content: new Text("Alert Dialog body"),
          actions: <Widget>[
            // usually buttons at the bottom of the dialog
            new FlatButton(
              child: new Text("Close"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

我试图在主屏幕小部件的build方法中调用该方法,但它给了我错误-

 The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
E/flutter ( 3667): #0      Navigator.of.<anonymous closure> (package:flutter/src/widgets/navigator.dart:1179:9)
E/flutter ( 3667): #1      Navigator.of (package:flutter/src/widgets/navigator.dart:1186:6)
E/flutter ( 3667): #2      showDialog (package:flutter/src/material/dialog.dart:642:20)

问题是我不知道从哪里调用_showDialog方法?


阅读 254

收藏
2020-08-13

共1个答案

一尘不染

我把它放在initState一个State(的StatefulWidget)。

将其放置在小部件的build方法中Stateless很诱人,但这将多次触发您的警报。

在下面的示例中,当设备未连接到Wifi时,它将显示警报,如果未连接,则显示[重试]按钮。

import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';

void main() => runApp(MaterialApp(title: "Wifi Check", home: MyPage()));

class MyPage extends StatefulWidget {
    @override
    _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
    bool _tryAgain = false;

    @override
    void initState() {
      super.initState();
      _checkWifi();
    }

    _checkWifi() async {
      // the method below returns a Future
      var connectivityResult = await (new Connectivity().checkConnectivity());
      bool connectedToWifi = (connectivityResult == ConnectivityResult.wifi);
      if (!connectedToWifi) {
        _showAlert(context);
      }
      if (_tryAgain != !connectedToWifi) {
        setState(() => _tryAgain = !connectedToWifi);
      }
    }

    @override
    Widget build(BuildContext context) {
      var body = Container(
        alignment: Alignment.center,
        child: _tryAgain
          ? RaisedButton(
              child: Text("Try again"),
              onPressed: () {
                _checkWifi();
            })
          : Text("This device is connected to Wifi"),
      );

      return Scaffold(
        appBar: AppBar(title: Text("Wifi check")),
        body: body
      );
    }

    void _showAlert(BuildContext context) {
      showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text("Wifi"),
            content: Text("Wifi not detected. Please activate it."),
          )
      );
    }
}
2020-08-13