I am new to flutter and still learning. I am trying to get reference of SharedPreferences instance but I am getting following error
_CastError (Null check operator used on a null value)
This is how my code looks like
app_settings.dart
class AppSettings {
final SharedPreferences _pref;
AppSettings._(this._pref);
static AppSettings? _instance;
static initialize() async {
if (_instance != null) {
// already initialized
return;
}
// instance not found. creating one
var pref = await SharedPreferences.getInstance();
_instance = AppSettings._(pref);
}
}
main.dart
Future<void> main() async {
// initializing application settings
await AppSettings.initialize();
runApp(App());
}
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "hello app",
home: AppHome());
}
}
Upon further debugging I found that the exception is being thrown by invokeMapMethod in
flutter-sdk/flutter/packages/flutter/lib/src/services/platform_channel.dart
which is called by getAll method in
flutter-sdk/flutter/.pub-cache/hosted/pub.dartlang.org/shared_preferences_platform_interface-2.0.0/lib/method_channel_shared_preferences.dart
Below are the screenshots of error