Home > Software design >  How to load json file before runapp in flutter?
How to load json file before runapp in flutter?

Time:10-17

I have to load json content before runApp in main of my flutter app. I have a Future function (LoadLanguage) which load json file in a variable(LanguageData) , so I can use value of mentioned variable in my app:

Future<void> LoadLanguage(BuildContext context,String lng)
async {
  String data = await DefaultAssetBundle.of(context).loadString("assets/translations/" lng ".json");
  LanguageData = jsonDecode(data);
}

problem is my app must wait until LanguageData be loaded.But I can't use LoadLanguage function before loading app , because there is no context in main() function. How can I use LoadLanguage in main() ?

CodePudding user response:

I could suggest another approach. Calling LoadLanguage() in didChangeDependencies () method or the initState(). Both of these execute before build() and therefore you could load whatever it is other parts of your app need in them so that when build() executes, your data is present.

  • Related