Home > Software engineering >  can i define sharedPreferences once and call it when i need data to display into flutter app?
can i define sharedPreferences once and call it when i need data to display into flutter app?

Time:01-16

i tried to declare the instance like this but it doesn't work

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

I would like to define the instance only once and call the global variable when i need

CodePudding user response:

declare it out the main method like this

late SharedPreferences appData;

and in the main assign it the instance like this

 void main() async{

 WidgetsFlutterBinding.ensureInitialized();
 appData = await SharedPreferences.getInstance();
 runApp(const MyApp());
 }

then you can use it any where you want

  • Related