Show alert dialog on app main screen load automatically in flutter

后端 未结 5 1369
遇见更好的自我
遇见更好的自我 2020-12-08 22:09

I want to show alert dialog based on a condition. Not based on user interaction such as button press event.

If a flag is set in app state data alert dialog is shown

5条回答
  •  长情又很酷
    2020-12-08 22:48

    I would place it in initState of a State (of a StatefulWidget).

    Placing it in the build method of a Stateless widget is tempting, but that will trigger your alert multiple times.

    In this example below, it displays an alert when the device is not connected to the Wifi, showing a [try again] button if it's not.

    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 {
        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."),
              )
          );
        }
    }
    

提交回复
热议问题