'timezone data not registered Flutter Local notification

New flutter Local Notification consisting of a Timezone-based time / Date Scheduling system for scheduled notification. I have created a file to include local notifications in my app. but it does not seems to work well. Showing an error when I call showDailyAtTime();

This is my notification plugin file.

import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io' show File, Platform;
import 'package:http/http.dart' as http;
import 'package:rxdart/subjects.dart';
import 'package:timezone/data/latest_all.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import 'package:flutter_native_timezone/flutter_native_timezone.dart';

class NotificationPlugin {
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
  final BehaviorSubject<ReceivedNotification>
      didReceivedLocalNotificationSubject =
      BehaviorSubject<ReceivedNotification>();
  var initializationSettings;
  NotificationPlugin._() {
    init();
  }
  init() async {
    flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
    if (Platform.isIOS) {
      _requestIOSPermission();
    }
    initializePlatformSpecifics();
  }

  initializePlatformSpecifics() {
    var initializationSettingsAndroid =
        AndroidInitializationSettings('app_notf_icon');
    var initializationSettingsIOS = IOSInitializationSettings(
      requestAlertPermission: true,
      requestBadgePermission: true,
      requestSoundPermission: false,
      onDidReceiveLocalNotification: (id, title, body, payload) async {
        ReceivedNotification receivedNotification = ReceivedNotification(
            id: id, title: title, body: body, payload: payload);
        didReceivedLocalNotificationSubject.add(receivedNotification);
      },
    );
    initializationSettings = InitializationSettings(
        android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
  }

  _requestIOSPermission() {
    flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            IOSFlutterLocalNotificationsPlugin>()
        .requestPermissions(
          alert: false,
          badge: true,
          sound: true,
        );
  }

  setListenerForLowerVersions(Function onNotificationInLowerVersions) {
    didReceivedLocalNotificationSubject.listen((receivedNotification) {
      onNotificationInLowerVersions(receivedNotification);
    });
  }

  setOnNotificationClick(Function onNotificationClick) async {
    await flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: (String payload) async {
      onNotificationClick(payload);
    });
  }

  Future<void> configureLocalTimeZone() async {
    tz.initializeTimeZones();
    final String timeZoneName = await FlutterNativeTimezone.getLocalTimezone();
    tz.setLocalLocation(tz.getLocation(timeZoneName));
  }

  tz.TZDateTime nextInstanceOfNotification(int hour, int minute) {
    final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
    tz.TZDateTime scheduledDate =
        tz.TZDateTime(tz.local, now.year, now.month, now.day, 10, 30);
    if (scheduledDate.isBefore(now)) {
      scheduledDate = scheduledDate.add(const Duration(days: 1));
    }
    print(tz.TZDateTime.now(tz.local).toString());
    print(scheduledDate.toString());

    return scheduledDate;
  }

  Future<void> showDailyAtTime() async {
    tz.initializeTimeZones();
    final String timeZoneName = await FlutterNativeTimezone.getLocalTimezone();
    tz.setLocalLocation(tz.getLocation(timeZoneName));

    var time = Time(21, 3, 0);
    var androidChannelSpecifics = AndroidNotificationDetails(
      'CHANNEL_ID 4',
      'CHANNEL_NAME 4',
      "CHANNEL_DESCRIPTION 4",
      importance: Importance.max,
      priority: Priority.high,
    );
    var iosChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
        android: androidChannelSpecifics, iOS: iosChannelSpecifics);
    await flutterLocalNotificationsPlugin.zonedSchedule(
      0,
      'Test Title at ${time.hour}:${time.minute}.${time.second}',
      'Test Body',
      tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
      platformChannelSpecifics,
      uiLocalNotificationDateInterpretation:
          UILocalNotificationDateInterpretation.absoluteTime,
      androidAllowWhileIdle: true,
      matchDateTimeComponents: DateTimeComponents.time,
      payload: 'Test Payload',
    );
  }

  Future<int> getPendingNotificationCount() async {
    List<PendingNotificationRequest> p =
        await flutterLocalNotificationsPlugin.pendingNotificationRequests();
    return p.length;
  }

  Future<void> cancelNotification() async {
    await flutterLocalNotificationsPlugin.cancel(0);
  }

  Future<void> cancelAllNotification() async {
    await flutterLocalNotificationsPlugin.cancelAll();
  }
}

NotificationPlugin notificationPlugin = NotificationPlugin._();

class ReceivedNotification {
  final int id;
  final String title;
  final String body;
  final String payload;
  ReceivedNotification({
    @required this.id,
    @required this.title,
    @required this.body,
    @required this.payload,
  });
}

This file I tried to call on my Main screen

import 'package:flutter/material.dart';
import './notification_plugin.dart';
import 'package:timezone/data/latest_all.dart' as tz;
import 'package:timezone/timezone.dart';

main() {
  tz.initializeTimeZones();
  final detroit = getLocation('America/Detroit');
  final now = new TZDateTime.now(detroit);
  runApp(MyNotificationApp());
}

class MyNotificationApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyApp(),
    );
  }
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  TextEditingController textController_tzDevice = TextEditingController()
    ..text = 'No Text';
  TextEditingController textController_tzSchedule = TextEditingController();

  @override
  void initState() {
    WidgetsFlutterBinding.ensureInitialized();
    // TODO: implement initState
    notificationPlugin.configureLocalTimeZone();
    notificationPlugin.showDailyAtTime();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My New App'),
      ),
      body: Center(
        child: Column(
          children: [
            TextField(
              controller: textController_tzDevice,
            ),
            TextField(
              controller: textController_tzSchedule,
            ),
            RaisedButton(
              child: Text('SET'),
              onPressed: () async {
                notificationPlugin.configureLocalTimeZone();
                notificationPlugin.showDailyAtTime();
              },
            )
          ],
        ),
      ),
    );
  }
}

Whats wrong with this?

Here is the errors:

Failed to handle method call
E/MethodChannel#dexterous.com/flutter/local_notifications( 6256): org.threeten.bp.zone.ZoneRulesException: No time-zone data files registered
E/MethodChannel#dexterous.com/flutter/local_notifications( 6256):   at org.threeten.bp.zone.ZoneRulesProvider.getProvider(ZoneRulesProvider.java:165)
E/MethodChannel#dexterous.com/flutter/local_notifications( 6256):   at org.threeten.bp.zone.ZoneRulesProvider.getRules(ZoneRulesProvider.java:122)
E/MethodChannel#dexterous.com/flutter/local_notifications( 6256):   at org.threeten.bp.ZoneRegion.ofId(ZoneRegion.java:143)
.....
..
E/flutter ( 6256): #0      StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:582
E/flutter ( 6256): #1      MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:159
E/flutter ( 6256): <asynchronous suspension>
E/flutter ( 6256): #2      MethodChannel.invokeMethod
package:flutter/…/services/platform_channel.dart:332
E/flutter ( 6256): #3      AndroidFlutterLocalNotificationsPlugin.zonedSchedule
package:flutter_local_notifications/src/platform_flutter_local_notifications.dart:136
E/flutter ( 6256): #4      FlutterLocalNotificationsPlugin.zonedSchedule
package:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:304
E/flutter ( 6256): #5      NotificationPlugin.showDailyAtTime
package:notificaiton_app/notification_plugin.dart:104
E/flutter ( 6256): <asynchronous suspension>
E/flutter ( 6256): #6      _MyAppState.build.<anonymous closure>
package:notificaiton_app/main.dart:60
E/flutter ( 6256): #7      _MyAppState.build.<anonymous closure>
package:notificaiton_app/main.dart:58

If I am wrong, please give me any detailed article or video. Because I cannot find anything related to this new update of local notification. all videos or articles are covering the normal DateTime schedule which is deprecated by the new update.



Solution 1:[1]

Please check this below answered:

From the logs, it seems that the app sometimes calls zonedSchedule() before initialize().

https://github.com/MaikuB/flutter_local_notifications/issues/1149

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Faisal Ahmed