How can I have my change notifier trigger my alert dialog?

Issue

I have a notification service which is a change notifier. When the service recieves a notification it notifies all listners. I want to display a dialog when the listners get notified. So I do the following in my build method

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

This is the shownotification method

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

So but this throws an error because I want to build the dialog while I am building Unhandled Exception: setState() or markNeedsBuild() called during build.

I do like using the change notifier provider. So how could I make this work?

Solution

You can use the SchedulerBinding.instance Api of Flutter to prevent this exception. The error happens because before the build method was built, you called a dialog that will prevent the reconstruction from finishing.

So there is no error:

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

However, the Flutter documentation recommends that you do not perform functions within the build method. this can have side effects.
You are probably using this approach because of the context required by the dialog. I recommend taking a look at this plugin:

https://pub.dev/packages/get

With it you can open dialogs from anywhere in your code, without the need for context, and its state manager is easier than changeNotifier, but it’s not that bad of performance.

According to the documentation, changeNotifier must be used on one, or a maximum of two listeners. His performance is very bad, and that of this plugin is very similar, but without using changeNotifier, I believe that this will make your project evolve a little more.

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

Answered By – jonatas Borges

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *