0
votes

I'm trying to set langauge from a Future call. I can see that future returns an object with data(value has languageCode property and it's data) but I cannot set that data to a String variable

 class Api {
  String language() {
  String langaugeCode;
  getLocale().then((value) => langaugeCode = value.languageCode);

  return langaugeCode;
 }

 
 Future<List<Product>> getProduct() async {
  var response = await http.get(BASE_URL + 'language?begins-with=' + language() , headers: headers());
 }

}
2
where are you using language()? add that code too - Faiizii Awan
updated my question @FaiiziiAwan - Gvep

2 Answers

2
votes

In order to set the value getLocale() returns to languageCode so it can be returned by language() you need to make language() async and await the result of language():

 Future<String> language() async {
  String langaugeCode;

  final locale = await getLocale();

  langaugeCode = locale.languageCode;

  return langaugeCode;
 }

The issue with the code in the question is that you get the value but only within the scope of the function passed into then(). Additionally language() is synchronous so it doesn't wait for getLocale() or its then() callback to execute before returning. This means the languageCode isn't available by the time the function returns a value.

Using this approach you'll also need to make sure that you only use language() in async functions and await it's result to get the value: await language().

2
votes
Future<String> language() async {  
  var local  = await getLocale()
  return local.languageCode;
}

 
 Future<List<Product>> getProduct() async {
  var lang = await language()
  var response = await http.get(BASE_URL + 'language?begins-with=' + lang , headers: headers());
 }