Search code examples
flutterdartcastingflutter-local-notification

How to cast Future<Null> to Future<dynamic> in Flutter while using flutter_local_notifications?


I was working with flutter_local_notifications plugin in flutter and while initializing it I got this error.

The argument type 'Future<Null> Function(int, String, String, String)' can't be assigned to the parameter type 'Future<dynamic> Function(int, String?, String?, String?)?'

The code I am using is:

void main() async {
  SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom]);
  WidgetsFlutterBinding.ensureInitialized();

  WidgetsFlutterBinding.ensureInitialized();

  var initializationSettingsAndroid = AndroidInitializationSettings('logo');
  var initializationSettingsIOS = IOSInitializationSettings(
      requestAlertPermission: true,
      requestBadgePermission: true,
      requestSoundPermission: true,
      onDidReceiveLocalNotification:
          (int id, String title, String body, String payload) async {}),//Error on this line
          
        
  var initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
  await flutterLocalNotificationsPlugin.initialize(initializationSettings,
      onSelectNotification: (String payload) async {
    if (payload != null) {
      debugPrint('notification payload: ' + payload);
    }
  });
  runApp(MyApp());
}

Is there a way to cast Future to Future in this function>?
Help will be really Appreciated. Thanks!


Solution

  • Seems like you are using the null safe version of that package.

    With the introduction of null-safety and Nullable types you need to carefully check what parameters that the packages are providing.

    The onDidReceiveLocalNotification doesn't guarantee that the title, body and payload would not be null. That is why the definition is as such inside their code,

    typedef DidReceiveLocalNotificationCallback 
      = Future<dynamic> Function(int id, String? title, String? body, String? payload);
    

    Notice the ? symbol which signifies that they are Nullable types, so you should define your callback in the same fashion.

    Change your code to this,

    onDidReceiveLocalNotification:
          (int id, String? title, String? body, String? payload) async {})