Show alert dialog on app main screen load automatically in flutter

后端 未结 5 1348
遇见更好的自我
遇见更好的自我 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:46

    Simply override initState and call your _showDialog method inside Timer.run()

    @override
    void initState() {
      super.initState();
      Timer.run(() => _showDialog());
    }
    
    0 讨论(0)
  • 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<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."),
              )
          );
        }
    }
    
    0 讨论(0)
  • 2020-12-08 22:52

    This is how I achieved this in a simple way:

    1. Add https://pub.dev/packages/shared_preferences

    2. Above the build method of your main screen (or any desired widget):

      Future checkFirstRun(BuildContext context) async {
       SharedPreferences prefs = await SharedPreferences.getInstance();
       bool isFirstRun = prefs.getBool('isFirstRun') ?? true;
      
       if (isFirstRun) {
         // Whatever you want to do, E.g. Navigator.push()
         prefs.setBool('isFirstRun', false);
       } else {
         return null;
       }
      }
      
    3. Then on your widget's initState:

      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance.addPostFrameCallback((_) => checkFirstRun(context));
      }
      

    This ensures the function is run after the widget is built.

    0 讨论(0)
  • 2020-12-08 22:55

    I solved it using a package developed by Flutter Community. here https://pub.dev/packages/after_layout

    Add this to your pubspec.yaml

    after_layout: ^1.0.7+2
    

    And try below example

    import 'package:after_layout/after_layout.dart';
    import 'package:flutter/material.dart';
    
    class DialogDemo extends StatefulWidget {
      @override
      _DialogDemoState createState() => _DialogDemoState();
    }
    
    class _DialogDemoState extends State<DialogDemo>
        with AfterLayoutMixin<DialogDemo> {
      @override
      void initState() {
        super.initState();
      }
    
      @override
      void afterFirstLayout(BuildContext context) {
        _neverSatisfied();
      }
    
      @override
      Widget build(BuildContext context) {
        return SafeArea(
          child: Container(
            decoration: BoxDecoration(color: Colors.red),
          ),
        );
      }
    
      Future<void> _neverSatisfied() async {
        return showDialog<void>(
          context: context,
          barrierDismissible: false, // user must tap button!
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('Rewind and remember'),
              content: SingleChildScrollView(
                child: ListBody(
                  children: <Widget>[
                    Text('You will never be satisfied.'),
                    Text('You\’re like me. I’m never satisfied.'),
                  ],
                ),
              ),
              actions: <Widget>[
                FlatButton(
                  child: Text('Regret'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      }
    }
    
    0 讨论(0)
  • 2020-12-08 23:00

    You have to wrap the content inside another Widget (preferably Stateless).

    Example:

    Change From:

      import 'package:flutter/material.dart';
    
      void main() {
        runApp(new MyApp());
      }
    
      class MyApp extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
          return MaterialApp(
              title: 'Trial',
              home: Scaffold(
                  appBar: AppBar(title: Text('List scroll')),
                  body: Container(
                    child: Text("Hello world"),
                  )));
        }
      }
    

    to this:

      import 'dart:async';
      import 'package:flutter/material.dart';
    
      void main() {
        runApp(new MyApp());
      }
    
      class MyApp extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
          return MaterialApp(
              title: 'Trial',
              home: Scaffold(
                  appBar: AppBar(title: Text('List scroll')), body: new MyHome()));
        }
      }
    
      class MyHome extends StatelessWidget { // Wrapper Widget
        @override
        Widget build(BuildContext context) {
          Future.delayed(Duration.zero, () => showAlert(context));
          return Container(
            child: Text("Hello world"),
          );
        }
    
        void showAlert(BuildContext context) {
          showDialog(
              context: context,
              builder: (context) => AlertDialog(
                    content: Text("hi"),
                  ));
        }
      }
    

    Note: Refer here for wrapping show alert inside Future.delayed(Duration.zero,..)

    0 讨论(0)
提交回复
热议问题