0

I have a GlobalVariables.dart where i store all the global variables.

library lumieres.globals;


String appLanguage;
bool languageChanged = false;
String appMode = 'dev';

in my main.dart file, I'm checking if shared preference contains 'user', if not I am setting the language to be english.

import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

import 'package:intl/intl.dart';
import 'GlobalVariables.dart' as globals;



// void main() => runApp(MyApp());

void main(){

  runApp(MyApp());

  startingAppFunction();

}


startingAppFunction() async{


  print('calling startingappfunction from main');
  SharedPreferences sharedpref = await SharedPreferences.getInstance();
  var user = sharedpref.getString('user');

   if (user != "" && user != null) {
      var decodedUser = json.decode(user);

      globals.appLanguage = decodedUser['lang'];


   }else{

     globals.appLanguage = "EN";
   }

   print('here is the app language from main dart');
   print(globals.appLanguage); //prints EN which is correct but on homepage it says null


}

But in my homepage, it's set back to null seems like the global variable is some how getting set back to String appLanguage; which is null.

import 'GlobalVariables.dart' as globals;



class HomePage extends StatefulWidget {

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  //limiting all results to only 6

  // var refreshKey = GlobalKey<RefreshIndicatorState>();
   Future<String> dataFuture;

  @override
  void initState(){
    super.initState();



  print('printing from home page...');

  print(globals.appLanguage); //prints null

 }

}

what am I missing? I followed this suggestion from this stackoverflow answer: Global Variables in Dart

Manas
  • 3,060
  • 4
  • 27
  • 55

1 Answers1

1

It might not be that it is set back to null but because it is an async process your print execute before your value is set. Your print in startingApp will always display the correct value because it is in the same method. Try running startingAppFunction() before your runApp(). (using then might be a good option too)

void main(){
    startingAppFunction().then((_) {
        runApp(MyApp());
    });
}
Guillaume Roux
  • 6,352
  • 1
  • 13
  • 38