Show alert dialog on app main screen load automatically in flutter

后端 未结 5 1365
遇见更好的自我
遇见更好的自我 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: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
        with AfterLayoutMixin {
      @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 _neverSatisfied() async {
        return showDialog(
          context: context,
          barrierDismissible: false, // user must tap button!
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('Rewind and remember'),
              content: SingleChildScrollView(
                child: ListBody(
                  children: [
                    Text('You will never be satisfied.'),
                    Text('You\’re like me. I’m never satisfied.'),
                  ],
                ),
              ),
              actions: [
                FlatButton(
                  child: Text('Regret'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      }
    }
    

提交回复
热议问题