zol*_*n21 8 android asynchronous flutter flutter-workmanager
我正在构建一个应用程序,通知用户祈祷时间。我正在使用 adhan 包来计算时间并将其保存在共享首选项中。由于祈祷时间每 24 小时变化一次,因此我使用 Workmanager 获取该特定时间的祈祷时间,并每 20 小时将其保存在共享偏好中。但我面临这个问题,有没有其他或更好的方法可以实现这一目标。
\nLaunching lib/main.dart on ASUS X00T in debug mode...\n\xe2\x9c\x93 Built build/app/outputs/flutter-apk/app-debug.apk.\nConnecting to VM Service at ws://127.0.0.1:44753/d5gE32RyvC4=/ws\nI/.example.notif(14281): Waiting for a blocking GC ProfileSaver\nE/flutter (14281): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Invalid argument(s) (input): Must not be null\n[38;5;244mE/flutter (14281): #0 _RegExp.firstMatch (dart:core-patch/regexp_patch.dart:221:24)[39;49m\n[38;5;244mE/flutter (14281): #1 DateTime.parse (dart:core/date_time.dart:266:23)[39;49m\n[38;5;248mE/flutter (14281): #2 PrayerTime.getFajr[39;49m\nE/flutter (14281): <asynchronous suspension>\n[38;5;248mE/flutter (14281): #3 _GetPrayersPageState.loalData[39;49m\nE/flutter (14281): <asynchronous suspension>\nE/flutter (14281):\nE/cutils-trace(14281): Error opening trace file: No such file or directory (2)\nI/flutter (14281): getAndSavePrayerscallbackDispatcher\nI/flutter (14281): 2021-03-25 13:07:32.419749+0530\nI/flutter (14281): 2021-03-25 12:45:00.000+0530\nI/flutter (14281): 2021-03-25 20:04:00.000+0530\nI/flutter (14281): 2021-03-25 17:08:00.000+0530\nI/flutter (14281): 2021-03-25 20:04:00.000+0530\nE/flutter (14281): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: NoSuchMethodError: The method 'zonedSchedule' was called on null.\nE/flutter (14281): Receiver: null\nE/flutter (14281): Tried calling: zonedSchedule(0, "Title", "Body", Instance of 'TZDateTime', Instance of 'NotificationDetails', androidAllowWhileIdle: true, uiLocalNotificationDateInterpretation: Instance of 'UILocalNotificationDateInterpretation')\n[38;5;244mE/flutter (14281): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)[39;49m\n[38;5;248mE/flutter (14281): #1 NotificationManager.zonedNotification.<anonymous closure>[39;49m\n[38;5;248mE/flutter (14281): #2 NotificationManager.zonedNotification.<anonymous closure>[39;49m\n[38;5;244mE/flutter (14281): #3 List.forEach (dart:core-patch/growable_array.dart:403:8)[39;49m\n[38;5;248mE/flutter (14281): #4 NotificationManager.zonedNotification[39;49m\nE/flutter (14281): <asynchronous suspension>\n[38;5;248mE/flutter (14281): #5 callbackDispatcher.<anonymous closure>[39;49m\nE/flutter (14281): <asynchronous suspension>\n[38;5;244mE/flutter (14281): #6 MethodChannel._handleAsMethodCall[39;49m\nE/flutter (14281): <asynchronous suspension>\n[38;5;244mE/flutter (14281): #7 _DefaultBinaryMessenger.handlePlatformMessage[39;49m\nE/flutter (14281): <asynchronous suspension>\nE/flutter (14281):\nI/chatty (14281): uid=10412(com.example.notify) 2.ui identical 3 lines\nE/flutter (14281): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: NoSuchMethodError: The method 'zonedSchedule' was called on null.\nE/flutter (14281): Receiver: null\nE/flutter (14281): Tried calling: zonedSchedule(0, "Title", "Body", Instance of 'TZDateTime', Instance of 'NotificationDetails', androidAllowWhileIdle: true, uiLocalNotificationDateInterpretation: Instance of 'UILocalNotificationDateInterpretation')\n[38;5;244mE/flutter (14281): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)[39;49m\n[38;5;248mE/flutter (14281): #1 NotificationManager.zonedNotification.<anonymous closure>[39;49m\n[38;5;248mE/flutter (14281): #2 NotificationManager.zonedNotification.<anonymous closure>[39;49m\n[38;5;244mE/flutter (14281): #3 List.forEach (dart:core-patch/growable_array.dart:403:8)[39;49m\n[38;5;248mE/flutter (14281): #4 NotificationManager.zonedNotification[39;49m\nE/flutter (14281): <asynchronous suspension>\n[38;5;248mE/flutter (14281): #5 callbackDispatcher.<anonymous closure>[39;49m\nE/flutter (14281): <asynchronous suspension>\n[38;5;244mE/flutter (14281): #6 MethodChannel._handleAsMethodCall[39;49m\nE/flutter (14281): <asynchronous suspension>\n[38;5;244mE/flutter (14281): #7 _DefaultBinaryMessenger.handlePlatformMessage[39;49m\nE/flutter (14281): <asynchronous suspension>\nE/flutter (14281):\nI/WM-WorkerWrapper(14281): Worker result FAILURE for Work [ id=0a8091e2-1677-4fc9-9fbd-79468e004d97, tags={ be.tramckrijte.workmanager.BackgroundWorker } ]\n\nRun Code Online (Sandbox Code Playgroud)\n主程序.dart
\nimport 'dart:async';\nimport 'package:flutter/material.dart';\nimport 'package:notify/local_notification/manage_notification.dart';\nimport 'package:notify/prayer_times.dart';\nimport 'package:workmanager/workmanager.dart';\nimport 'package:timezone/timezone.dart' as tz;\n\nconst String uniqueName = "getPrayers";\nconst String taskName = "getAndSavePrayers";\n\nvoid main() {\n WidgetsFlutterBinding.ensureInitialized();\n Workmanager.initialize(callbackDispatcher, isInDebugMode: true);\n Workmanager.registerPeriodicTask(uniqueName, taskName,\n initialDelay: Duration(minutes: 1),\n frequency: Duration(hours: 20),\n constraints: Constraints(\n networkType: NetworkType.not_required,\n requiresBatteryNotLow: false,\n requiresCharging: false,\n requiresDeviceIdle: false,\n requiresStorageNotLow: false));\n runApp(MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n // This widget is the root of your application.\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: 'GetPrayer',\n theme: ThemeData(\n brightness: Brightness.dark,\n primarySwatch: Colors.cyan,\n ),\n home: GetPrayersPage(),\n );\n }\n}\n\nclass GetPrayersPage extends StatefulWidget {\n @override\n _GetPrayersPageState createState() => _GetPrayersPageState();\n}\n\nclass _GetPrayersPageState extends State<GetPrayersPage> {\n tz.TZDateTime fajr;\n tz.TZDateTime dhuhr;\n tz.TZDateTime maghrib;\n tz.TZDateTime asr;\n tz.TZDateTime isha;\n @override\n void initState() {\n super.initState();\n\n loalData();\n }\n\n void loalData() async {\n fajr = await PrayerTime.instance.getFajr();\n dhuhr = await PrayerTime.instance.getdhuhr();\n maghrib = await PrayerTime.instance.getmaghrib();\n asr = await PrayerTime.instance.getasr();\n isha = await PrayerTime.instance.getisha();\n setState(() {});\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: Text('Prayer times'),\n elevation: 0.0,\n ),\n body: Column(\n mainAxisSize: MainAxisSize.min,\n children: [\n ListTile(\n leading: Icon(Icons.calendar_today),\n title: Text("Fajr"),\n trailing: Text("${fajr.toString()}"),\n ),\n ListTile(\n leading: Icon(Icons.calendar_today),\n title: Text("Dhuhr"),\n trailing: Text("${dhuhr.toString()}"),\n ),\n ListTile(\n leading: Icon(Icons.calendar_today),\n title: Text("Maghrib"),\n trailing: Text("${maghrib.toString()}"),\n ),\n ListTile(\n leading: Icon(Icons.calendar_today),\n title: Text("Asr"),\n trailing: Text("${asr.toString()}"),\n ),\n ListTile(\n leading: Icon(Icons.calendar_today),\n title: Text("Isha"),\n trailing: Text("${isha.toString()}"),\n ),\n ],\n ),\n bottomNavigationBar: Container(\n child: ElevatedButton(\n style: ButtonStyle(\n minimumSize:\n MaterialStateProperty.all(Size(double.infinity, 60))),\n onPressed: () {\n PrayerTime.instance.getPrayers();\n },\n child: Text("UPDATE"),\n ),\n ),\n );\n }\n}\n\nvoid callbackDispatcher() {\n Workmanager.executeTask((task, inputData) async {\n switch (task) {\n case taskName:\n PrayerTime.instance.getPrayers();\n await NotificationManager().initNotificationManager();\n await NotificationManager().zonedNotification();\n await NotificationManager().showNotification();\n break;\n }\n return Future.value(true);\n });\n print(taskName + "callbackDispatcher");\n}\n\nRun Code Online (Sandbox Code Playgroud)\n祈祷时间.dart
\nimport 'package:adhan/adhan.dart';\nimport 'package:notify/local_notification/get_timezone_date.dart';\nimport 'package:shared_preferences/shared_preferences.dart';\nimport 'package:timezone/timezone.dart' as tz;\n\nclass PrayerTime {\n static const String fajrKey = "fajr";\n static const String sunriseKey = "sunrise";\n static const String dhuhrKey = "dhuhr";\n static const String asrKey = "asr";\n static const String maghribKey = "maghrib";\n static const String ishaKey = "maghrib";\n\n PrayerTime._privateConstructor();\n\n static final PrayerTime _instance = PrayerTime._privateConstructor();\n\n static PrayerTime get instance => _instance;\n\n List<String> prayerTimesList = [];\n\n void getPrayers() async {\n final myCoordinates = Coordinates(19.076090, 72.877426);\n final params = CalculationMethod.karachi.getParameters();\n params.madhab = Madhab.hanafi;\n final prayerTimes = PrayerTimes.today(myCoordinates, params);\n final datewa = DateTime.now().add(Duration(minutes: 5));\n String _formatTime(DateTime time) {\n return time.toIso8601String();\n }\n\n savePrayers(\n fajr: _formatTime(datewa),\n // fajr: _formatTime(prayerTimes.fajr),\n dhuhr: _formatTime(prayerTimes.dhuhr),\n asr: _formatTime(prayerTimes.asr),\n maghrib: _formatTime(prayerTimes.maghrib),\n isha: _formatTime(prayerTimes.isha),\n );\n }\n\n void savePrayers({\n String fajr,\n String dhuhr,\n String asr,\n String maghrib,\n String isha,\n }) async {\n SharedPreferences prefs = await SharedPreferences.getInstance();\n await prefs.setString(fajrKey, fajr);\n await prefs.setString(dhuhrKey, dhuhr);\n await prefs.setString(asrKey, asr);\n await prefs.setString(maghribKey, maghrib);\n await prefs.setString(ishaKey, isha);\n }\n\n Future<tz.TZDateTime> getFajr() async {\n SharedPreferences prefs = await SharedPreferences.getInstance();\n return convertToTZ(DateTime.parse(prefs.getString(fajrKey)));\n }\n\n Future<tz.TZDateTime> getdhuhr() async {\n SharedPreferences prefs = await SharedPreferences.getInstance();\n return convertToTZ(DateTime.parse(prefs.getString(dhuhrKey)));\n }\n\n Future<tz.TZDateTime> getasr() async {\n SharedPreferences prefs = await SharedPreferences.getInstance();\n return convertToTZ(DateTime.parse(prefs.getString(asrKey)));\n }\n\n Future<tz.TZDateTime> getmaghrib() async {\n SharedPreferences prefs = await SharedPreferences.getInstance();\n return convertToTZ(DateTime.parse(prefs.getString(maghribKey)));\n }\n\n Future<tz.TZDateTime> getisha() async {\n SharedPreferences prefs = await SharedPreferences.getInstance();\n return convertToTZ(DateTime.parse(prefs.getString(ishaKey)));\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n管理通知.dart
\nimport 'dart:typed_data';\nimport 'package:flutter/material.dart';\nimport 'package:flutter_local_notifications/flutter_local_notifications.dart';\nimport 'package:notify/prayer_times.dart';\nimport 'package:timezone/timezone.dart' as tz;\n\nclass NotificationManager {\n FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;\n AndroidInitializationSettings initializationSettingsAndroid;\n IOSInitializationSettings initializationSettingsIOS;\n InitializationSettings initializationSettings;\n\n /// Initializing FlutterLocalNotificationsPlugin.\n Future initNotificationManager() async {\n flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();\n initializationSettingsAndroid =\n AndroidInitializationSettings('ic_launcher');\n initializationSettingsIOS = IOSInitializationSettings();\n initializationSettings = InitializationSettings(\n android: initializationSettingsAndroid, iOS: initializationSettingsIOS);\n await flutterLocalNotificationsPlugin.initialize(initializationSettings);\n }\n\n Future<void> zonedNotification() async {\n /// List of prayer times.\n List<tz.TZDateTime> _times = [\n await PrayerTime.instance.getFajr(),\n await PrayerTime.instance.getdhuhr(),\n await PrayerTime.instance.getmaghrib(),\n await PrayerTime.instance.getasr(),\n await PrayerTime.instance.getisha(),\n ];\n\n /// Vibration pattern.\n var vibrationPattern = Int64List(4);\n vibrationPattern[0] = 0;\n vibrationPattern[1] = 1000;\n vibrationPattern[2] = 5000;\n vibrationPattern[3] = 2000;\n\n /// Android Specifics.\n var androidPlatformChannelSpecifics = AndroidNotificationDetails(\n "0", "channel Name", "channel Description",\n icon: 'ic_launcher',\n sound: RawResourceAndroidNotificationSound("slow_spring_board"),\n largeIcon: DrawableResourceAndroidBitmap('ic_launcher'),\n vibrationPattern: vibrationPattern,\n autoCancel: false,\n enableLights: true,\n playSound: true,\n color: Colors.green,\n ledColor: const Color.fromARGB(255, 255, 0, 0),\n ledOnMs: 1000,\n ledOffMs: 500);\n\n /// iOS Specifics.\n IOSNotificationDetails iOSPlatformChannelSpecifics =\n IOSNotificationDetails(sound: 'slow_spring_board.aiff');\n\n /// Platform channel specifics.\n NotificationDetails platformChannelSpecifics = NotificationDetails(\n android: androidPlatformChannelSpecifics,\n iOS: iOSPlatformChannelSpecifics);\n\n /// ZonedSchedule\n _times.forEach((element) async {\n await flutterLocalNotificationsPlugin.zonedSchedule(\n 0, "Title", "Body", element, platformChannelSpecifics,\n uiLocalNotificationDateInterpretation:\n UILocalNotificationDateInterpretation.absoluteTime,\n androidAllowWhileIdle: true);\n });\n }\n\n Future<void> showNotification() async {\n var androidPlatformChannelSpecifics = AndroidNotificationDetails(\n "1", 'channel name', 'channel description',\n importance: Importance.high, priority: Priority.high, ticker: 'ticker');\n var iOSPlatformChannelSpecifics = IOSNotificationDetails();\n var platformChannelSpecifics = NotificationDetails(\n android: androidPlatformChannelSpecifics,\n iOS: iOSPlatformChannelSpecifics);\n await flutterLocalNotificationsPlugin.show(\n 0, 'plain title', 'plain body', platformChannelSpecifics,\n payload: 'item x');\n }\n}\n\nRun Code Online (Sandbox Code Playgroud)\n获取时区.dart
\nimport 'package:timezone/data/latest.dart';\nimport 'package:timezone/timezone.dart' as tz;\nimport 'package:flutter_native_timezone/flutter_native_timezone.dart';\n\nclass TimeZone {\n factory TimeZone() => _this ?? TimeZone._();\n\n TimeZone._() {\n initializeTimeZones();\n }\n static TimeZone _this;\n\n Future<String> getTimeZoneName() async =>\n FlutterNativeTimezone.getLocalTimezone();\n\n Future<tz.Location> getLocation([String timeZoneName]) async {\n if (timeZoneName == null || timeZoneName.isEmpty) {\n timeZoneName = await getTimeZoneName();\n }\n return tz.getLocation(timeZoneName);\n }\n}\n\nFuture<tz.TZDateTime> convertToTZ(dateTime) async {\n final timeZone = TimeZone();\n String timeZoneName = await timeZone.getTimeZoneName();\n final location = await timeZone.getLocation(timeZoneName);\n final scheduledDate = tz.TZDateTime.from(dateTime, location);\n print(scheduledDate.toString());\n return scheduledDate;\n}\n\nRun Code Online (Sandbox Code Playgroud)\n扑医生
\nDoctor summary (to see all details, run flutter doctor -v):\n[\xe2\x9c\x93] Flutter (Channel stable, 2.0.1, on Linux, locale en_US.UTF-8)\n[\xe2\x9c\x93] Android toolchain - develop for Android devices (Android SDK version 30.0.3)\n[\xe2\x9c\x93] Chrome - develop for the web\n[!] Android Studio (not installed)\n[\xe2\x9c\x93] VS Code (version 1.54.3)\n[\xe2\x9c\x93] Connected device (2 available)\n\n! Doctor found issues in 1 category.\nRun Code Online (Sandbox Code Playgroud)\npubspec.yaml *
\nversion: 1.0.0+1\n\nenvironment:\n sdk: ">=2.7.0 <3.0.0"\n\ndependencies:\n flutter:\n sdk: flutter\n workmanager: ^0.2.3\n shared_preferences: ^2.0.5\n adhan: ^1.1.15\n intl: ^0.17.0\n background_location: ^0.4.1\n flutter_local_notifications: 4.0.1+2\n flutter_native_timezone: ^1.0.10\n # The following adds the Cupertino Icons font to your application.\n # Use the CupertinoIcons class for iOS style icons.\n cupertino_icons: ^1.0.2\n\ndev_dependencies:\n flutter_test:\n sdk: flutter\nRun Code Online (Sandbox Code Playgroud)\n
在 try/catch 中调用您的代码并查看错误并将实例设置为变量:
try {
PrayerTime.instance.getPrayers();
NotificationManager manager = new NotificationManager();
await manager.initNotificationManager();
await manager.zonedNotification();
await manager.showNotification();
} catch(e) {
print(e);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5556 次 |
| 最近记录: |