Home > other >  Flutter how to accesss a single SharedPreference instance through the whole app
Flutter how to accesss a single SharedPreference instance through the whole app

Time:07-11

I'm using SharedPreferences to store settings data, problem is that I need to access this data in multiple different locations & right now I need a new futurebuilder for every different screen I need to access the data from..

Is there anyway to only get SharedPreference data ONCE & then access that instance throughout the app instead of having a bunch of futurebuilders everywhere?

CodePudding user response:

You can create a file called globals.dart and create a SharedPreferences variable without setting it:

globals.dart

SharedPreferences? sharedPreferences;

Then, in your main.dart instantiate your varaible sharedPreferences within your main() function:

main.dart

import './globals.dart';

void main() async {
  sharedPreferences = await SharedPreferences.getInstance();
  runApp(const MyApp());
}

Now you can call your global variable sharedPreferences in any file throughout your project as long as you import globals.dart:

sharedPreferences?.setString('key', 'value');
  • Related