【问题标题】:How can I have my change notifier trigger my alert dialog?如何让我的更改通知器触发我的警报对话框?
【发布时间】:2020-08-18 09:23:03
【问题描述】:

我有一个通知服务,它是一个更改通知器。当服务收到通知时,它会通知所有侦听器。我想在收听者收到通知时显示一个对话框。所以我在构建方法中执行以下操作

    Consumer<NotificationService>(
        builder: (BuildContext context, NotificationService notificationNotifier, _) {
            if (notificationNotifier.hasNotifications)  
                _showNotification(context, notificationNotifier.popNotification());
            return Scaffold(

这是shownotification方法

  Future<dynamic> _showNotification(BuildContext context, NotificationModel notification) async {
    try {
      print(notification.title);
      await PlatformAlertDialog(
        notification.title,
        notification.body,
      ).show(context);
    } on UserFriendlyException catch (error) {
      await PlatformAlertDialog(
        error.title,
        error.message,
      ).show(context);
    }
  }

但是这会引发错误,因为我想在构建Unhandled Exception: setState() or markNeedsBuild() called during build.时构建对话框@

我确实喜欢使用更改通知提供程序。那么我怎样才能完成这项工作呢?

【问题讨论】:

    标签: flutter dart flutter-change-notifier


    【解决方案1】:

    你可以使用 Flutter 的 SchedulerBinding.instance Api 来防止这个异常。发生错误是因为在构建构建方法之前,您调用了一个对话框,该对话框将阻止重建完成。

    所以没有错误:

    Consumer<NotificationService>(
            builder: (BuildContext context, NotificationService notificationNotifier, _) {
                if (notificationNotifier.hasNotifications){  
                     SchedulerBinding.instance.addPostFrameCallback((_) =>  
                   _showNotification(context, notificationNotifier.popNotification()));
                   }
                return Scaffold(
    

    但是,Flutter 文档建议您不要在 build 方法中执行功能。这可能会产生副作用。 由于对话框所需的上下文,您可能正在使用这种方法。我建议看看这个插件:

    https://pub.dev/packages/get

    有了它,您可以从代码中的任何位置打开对话框,无需上下文,而且它的状态管理器比 changeNotifier 更容易,但性能还不错。

    根据文档,changeNotifier 必须用于一个或最多两个侦听器。他的表现很差,和这个插件很相似,但是不使用changeNotifier,我相信这会让你的项目进步一点。

    https://api.flutter.dev/flutter/foundation/ChangeNotifier-class.html

    【讨论】:

      猜你喜欢
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多