Flutter : How can use String data outside future method? - flutter

I have this future method to get a data from server and using it :
Future<String> get_week() async {
var weekUrl =
'https://xxx/api/controller/matchs/active_week.php';
var weekresponse = await http.get(weekUrl);
var weekdata = await jsonDecode(weekresponse.body);
var weekId = weekdata[0]['w_id'];
return weeId
}
How can i use the value of weekId outside this method?

You can use the await keyword to assign the returned value from the future to variable:
String id = await get_week();

Related

How to have a flutter class method return a future?

How do I set up a flutter method to return a future value that is drawn from the results of a future http post call inside the method?
The example code below is making a call to a web URL to add a new product. I want this method to return just the Id of the newly created product (i.e. 'name' inside response)
Future<String> add(Product aNewProduct) async {
var aUrl = Uri.parse(dbUrl);
http.post(aUrl,body: toBody(aNewProduct),).then((response) {
var aStr = json.decode(response.body)['name'];
return Future<String>.value(aStr);
});
}
With the code above, the parser is showing the following error/warning...
The body might complete normally, causing 'null' to be returned,
but the return type, 'FutureOr<String>', is a potentially non-nullable type.
(Documentation) Try adding either a return or a throw statement at the end.
Any suggestions on how to fix this?
You can use the await to get the value of a Future or rather your http request. After that you can simple decode it and return your desired behavior.
Future<String> add(Product aNewProduct) async {
var aUrl = Uri.parse(dbUrl);
final response = http.post(
aUrl,
body: toBody(aNewProduct),
);
return json.decode(response.body)['name'];
}
try this:
Future<String> add(Product aNewProduct) async {
var aUrl = Uri.parse(dbUrl);
var response= await http.post(aUrl,body: toBody(aNewProduct),);
if(response.statusCode==200){
var rawData = await response.stream.bytesToString();
Map data=json.decode(rawData);
return data['name'];
}else{
return '';
}
}
It is as simple as putting a return before the http.post statement

Exception in json.decode : Closure: () => String from Function 'toString'

I am getting some data from API in flutter. I am trying to decode the data using json.decode() but this decode function gives me the following error:
Closure: () => String from Function 'toString'
Here's my code:
Future<Product> createOrder() async {
var client = new http.Client();
var productModel = null;
try {
var response = await client
.get(Uri.https('butterbasket.onrender.com', Strings.createOrderUrl));
if (response.statusCode == 200) {
var body = response.body;
print("Body: $body");
var jsonMap = json.decode(body);
var productModel = Product.fromJson(jsonMap);
}
} catch (e) {
print("Exception: ${e.toString}");
}
return productModel;
}
Here is the Error Debug Console:
You are running into issues because the data you are loading in is an array, but the model is an object. You'll need to do something like the following:
final List jsonProducts = json.decode(body)
final List<Product> products =
jsonProducts.map((jsonProduct) => Product.fromJson(jsonProduct)).toList();
and then if you only need the first item you can do:
final Product product = products[0]
But don't forget to check if the array is big enough.
Your Future function must return an optional Product?, otherwise your future will never find a result as you are declaring it inside the function.
Instead of:
Future<Product> createOrder() async {}
Use:
Future<Product?> createOrder() async {}
Finally your async snapshot and FutureBuilder type should be of type <Product?>.

I want to get the field data from FireStore

I want to get ['startTime] in this method.
But I can't get it.
I get the following error
The method 'data' isn't defined for the type 'Future'. Try correcting
the name to the name of an existing method, or defining a method named
'data'.
Future<String> getStudyTime()async {
final getStartTime =
await FirebaseFirestore.instance.collection('user').doc(uid()).get().data()['startTime'];
final DateTime now = DateTime.now();
final formatTime = DateFormat('hh:mm a').format(now);
var hh = now.hour;
var mm = now.minute;
var hhmm = "$hh:$mm";
studyTime = int.parse(hhmm);
return studyTime;
}
[FireStore Image]
Calling get() returns a Future, so you need to use await on get to get its value:
final doc = await FirebaseFirestore.instance.collection('user').doc(uid()).get();
final getStartTime = doc.data()['startTime'];
If you want to do this in a single line, use parenthesis to ensure the await works on get():
final getStartTime =
await (FirebaseFirestore.instance.collection('user').doc(uid()).get()).data()['startTime'];

Trying to create a method to store Strings in a list

i have a list of volumes that looks like this
['9v9JXgmM3F0C','RoAwAAAAYAAJ','RYAwAAAAYAAJ']
i have a ready funtion that sends Individual volumes and retruns a Map.
Future<BookIdVolume> getBooksByVolume(volume) async {
var searchUrl = 'https://www.googleapis.com/books/v1/volumes/$volume';
var response = await http.get(searchUrl);
var responseBody = jsonDecode(response.body);
return BookIdVolume.fromJson(responseBody);
}
Im trying to create a method to store each of volumes in a list and retrun it.
I have tryed using loops for and forEach but it keeps retruning either [] or null
im i doing somthing wong ? is thier a better better way to do it ?
I'm guessing you're getting null back because you're not building the url properly for each volume. Try this.
final volumeList = ['9v9JXgmM3F0C', 'RoAwAAAAYAAJ', 'RYAwAAAAYAAJ'];
final baseUrl = 'https://www.googleapis.com/books/v1/volumes/';
List<BookIdVolume> bookList = [];
void buildBookList() async {
for (String volume in volumeList) {
final url = '$baseUrl$volume';
final book = await getBooksByVolume(url);
bookList.add(book);
}
}
Then you remove the first line from the getBooksByVolume function because you're already sending the full url.
Future<BookIdVolume> getBooksByVolume(url) async {
var response = await http.get(url);
var responseBody = jsonDecode(response.body);
return BookIdVolume.fromJson(responseBody);
}

flutter future do not set data

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());
}
}
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());
}
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().