1

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

    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.

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

4

1 回答 1

2

您可以使用 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

于 2020-05-04T02:50:31.463 回答