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

2g32fytz  于 2023-01-31  发布在  Flutter
关注(0)|答案(6)|浏览(148)

我想显示基于条件的警报对话框。而不是基于用户交互,如按钮按下事件。
如果在应用程序状态数据中设置了标志,则显示警报对话框,否则不显示。
下面是我想要显示的警报对话框示例

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方法?

to94eoyn

to94eoyn1#

必须将内容 Package 在另一个Widget(最好是Stateless)中。

    • 示例:**
    • 变更自:**
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"),
              )));
    }
  }
    • 致:**
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"),
              ));
    }
  }

注:请参阅此处了解Future.delayed(Duration.zero,..)内的 Package 显示警报

bhmjp9jg

bhmjp9jg2#

只需覆盖initState并在FutureTimer中调用_showDialog方法:

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

  // Use either of them. 
  Future(_showDialog);
  Timer.run(_showDialog); // Requires import: 'dart:async'
}
mqkwyuun

mqkwyuun3#

我会把它放在StateinitState中(StatefulWidgetinitState中)。
将其放在Stateless小部件的build方法中很有吸引力,但这将多次触发警报。
在下面的示例中,当设备未连接到Wifi时,它会显示警报,如果未连接,则会显示[重试]按钮。

import 'package:flutter/material.dart';
import 'package:connectivity_plus/connectivity_plus.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."),
          )
      );
    }
}
dm7nw8vv

dm7nw8vv4#

这就是我如何用一种简单的方式实现这一点:
1.添加https://pub.dev/packages/shared_preferences
1.在主屏幕(或任何所需小部件)的构建方法上方:

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;
 }
}

1.然后在微件的initState上:

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

这确保了函数在构建小部件之后运行。

4c8rllxm

4c8rllxm5#

我用Flutter社区开发的软件包解决了这个问题。这里https://pub.dev/packages/after_layout
将此添加到您的pubspec.yaml

after_layout: ^1.0.7+2

并尝试以下示例

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();
              },
            ),
          ],
        );
      },
    );
  }
}
mbskvtky

mbskvtky6#

如果您正在使用块,请使用@mirkancal在此答案中建议的BlocListener:Flutter:块,如何显示警报对话框

相关问题