Reputation: 1
I am getting the below error while initializing the time zone in main method using flutter_native_timezone
.
Error:
Unhandled Exception: Null check operator used on a null value
MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:121:86)
MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:146:36)
MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
FlutterNativeTimezone.getLocalTimezone
(package:flutter_native_timezone/flutter_native_timezone.dart:17:24)
configureLocalTimeZone (package:myapp/main.dart:48:60)
main (package:myapp/main.dart:16:9)
runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:145:25)
rootRun (dart:async/zone.dart:1428:13)`enter code here`
CustomZone.run (dart:async/zone.dart:1328:19)
runZoned (dart:async/zone.dart:1863:10)
Using the below plugins:
package:timezone/data/latest_10y.dart as tz
package:timezone/timezone.dart as tz
Code Snippet:
Future<void> configureLocalTimeZone() async {
if (kIsWeb || Platform.isLinux) {
return;
}
tz.initializeTimeZones();
final String? timeZoneName = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(timeZoneName!));
}
Upvotes: 0
Views: 429
Reputation: 77304
Well, I guess you do not read your own code, or have simply not understood what dart null safety is. I strongly urge you to read and understand Dart nullsafety, this feature is here to stay and you will not be able to properly write code if you don't understand it. Dart null safety is not about randomly slapping ?
and !
on stuff until it compiles.
This line explicitely says that the variable timeZoneName
can be null:
final String? timeZoneName = await FlutterNativeTimezone.getLocalTimezone();
...and then in the very next line, you tell the compiler, pinky promise, I swear this variable will never be null.
tz.setLocalLocation(tz.getLocation(timeZoneName!));
Well, guess what happened? It was null. You lied to your compiler and the compiler caught you.
What can you do? Instead of lying to your compiler to make it compile, you could understand what you have to do to write a proper program. In this case, you need to insert an if
and only invoke your second line, if you have a timeZoneName
. What to do if you don't? I don't know, that is your job to decide. Maybe log an error message? But don't tell your compiler it is wrong. That will only lead to errors like the one you got.
Upvotes: 1