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