2

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

invokeMapMethod

getAll

Anshul Srivastava
  • 249
  • 2
  • 5
  • 11

3 Answers3

5

I was calling SharedPreferences.getInstance() before runApp(). Since platform-specific native bindings were not initialized, which are used by SharedPreferences, it was throwing a null exception. So I added WidgetsFlutterBinding.ensureInitialized() before calling await SharedPreferences.getInstance():

Future<void> main() async {
  // initializing application settings
  WidgetsFlutterBinding.ensureInitialized();
  await AppSettingService.initialize();
  runApp(WorkoutTrackerApp());
}

You can learn more from following links

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Anshul Srivastava
  • 249
  • 2
  • 5
  • 11
0

How about

static initialize async() {
  _instance = _instance?AppSettings(await SharedPreferences.getInstance());
}
Chris Reynolds
  • 5,453
  • 1
  • 15
  • 12
-1

Try:

if (preferences == null) return {} as Map;
Huthaifa Muayyad
  • 11,321
  • 3
  • 17
  • 49