How display data which comes from async function? - flutter

I use api for get information which need to be display
Future <String> Get_Amount_Jackpot() async {
// SERVER LOGIN API URL
var url2 = 'https://www.easytrafic.fr/game_app/get_jackpot_lotto.php';
// Starting Web API Call.
var response2 = await http.get(url2,headers: {'content-type': 'application/json','accept': 'application/json','authorization': globals.token});
// Getting Server response into variable.
Map<String, dynamic> jsondata2 = json.decode(response2.body);
return jsondata2["value"];
}
I call it here :
void initState() {
ListLotto = Grille_display();
jackpot = Get_Amount_Jackpot();
super.initState();;
}
How i can display the value "jackpot" which is a simple number on mobile screen. Note i use futurebuilder for another api request, this is why it is complicated. Normally i use futurebuilder for display async data but there i need 2 différents api request so 2 futureBuilder ??? Is it possible and how do that ?

You can use then to get the returned value from the function.
Get_Amount_Jackpot().then((value){
//value is what is returned from the function
jackpot = value;
});
I'm not sure if you can use uppercase letter as the start of a function name, but i copied your function name for my answer. Hope this helps.

Related

Flutter async rest api call in synchronised way

I have an API to fetch results based on some user typed text. I want api calls to run in syncronized way so last API call result should be in last.
Use case
User type #cbc
API is calling 4 time
#, #c, #cb and #cbc
Issue is API result is giving result randomly not in syncronized way.
Future<void> getHashtags(String tagName) async {
var params = jsonEncode(
{"tag_name": tagName, "latest_hashtag_community": true});
var response = await _postRepository.getHashTags(params,
pageNo: pageNumberHashtags);
}

Flutter - Riverpod. Save response from http in a provider

I new to Riverpod, and I have a basic question.
On the start up of my app, I make an http to load a preload. This returns a Json response, with basic stings and lists of string, data that is used around the app.
I make the request like this:
class PreLoadApi {
getPreloadList() {
http.get(url,
headers: {HttpHeaders.contentTypeHeader: "application/json", HttpHeaders.authorizationHeader: "Bearer $token"}
).then((http.Response response) {
int statusCode = response.statusCode;
print(statusCode);
log("2124: PreLoad. response.body:${response.body}");
var data = json.decode(response.body);
String name = data['name']
*** Here I want to save the string "name" to a provider. ***
}
Now I want to save this String name in a provider. I would like to make a provider like this:
final nameProvider = StateProvider((ref)=> name);
I want this, so that this string will be available all over the app.
However, providers have to been defined top level, so I'm not sure how to get the data there?
Meaning, in the above http request I make, in the .then function which is called on the result of the request, I want to store there the value into a provider. How to I create a provider there? Since the provider is global, I don't know how to save the result data String into the provider
I hope the question is clear, and thanks for the help!
To read a provider, you need a WidgetRef. You can pass it on getPreloadList . In this case it will be
final nameProvider = StateProvider.autoDispose((ref) => "");
class PreLoadApi {
getPreloadList(WidgetRef ref) {
//Future.delayed will be your http.get
Future.delayed(Duration(seconds: 3)).then((value) {
ref.read(nameProvider.notifier).state = "new Value";
});
}
}
To have a widgetRef you can wrap the widget with Consumer
return Consumer(
builder: (context, ref, child) => Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
PreLoadApi api = PreLoadApi();
api.getPreloadList(ref);
},
),
body: Text(ref.watch(nameProvider)),
There are others way handling this like getting text from future instead of passing WidgetRef. Also check StateNotifierProvider, ChangeNotifierProvider.
You can start from riverpod.dev
Because your "name" is valid only after a Future completes, the most likely holder for the value is a FutureProvider. Nicely, this will cache the value, as long as you don't make the provider autoDispose.

How to get named json response Flutter using http get method

ok here is my json format
{
"success":true,
"user":{
"name":"example"
"email:"example#email.com"
}
}
ok by using Chopper Flutter it was easy just to get the user object by calling
response.body["user"]
however the current Chopper version ie the null safety is not stable...so how do you call this method in HTTP? to get the user object only...
Response response = await http.get(Uri.parse('enterYourUrlHere');
Map<String, dynamic> body = jsonDecode(response.body);
var user = body['user'];
print(user['email']); // prints out example#email.com"

How to use List data returned from an API call

Im attempting to get back a list of data from an API call and send this list of data to a local sqlite database I've created for it. I'm getting an issue with the data being a type <List> and I'm not sure how to convert it to something usable. I'm just trying to assign that data from the api call to a variable so I can just simply send it to the sqlite database. Any advice is welcome! Thanks!
This is the code where I'm attempting to get that data from the API call and send it to the sqlite database.
if(user.success) {
Quarter quarters;
quarters = await getQuarters();
QuarterDBProvider.quarterDB.newQuarter(quarters);
}
This is where the API call is performed
Map data;
List<Quarter> quarterFromJson(String str) =>
List<Quarter>.from(json.decode(str).map((x) => Quarter.fromJson(x)));
Future<List<Quarter>> getQuarters() async {
final http.Response response = await http.get(
'https://myfakeapi/quarters',
);
if (response.statusCode < 400) {
return quarterFromJson(response.body);
} else {
throw Exception('Failed to get quarters');
}
}
the response from api is list and it is not String.
List<Quarter> _listQuarter= [];
var json = jsonDecode(response.body) as List<dynamic>;
json.forEach((element) {
_listQuarter.add( -do all your workaround- );
});
return _listQuarter;

How do I use Futures in Futures in Flutter?

Soo, the title might be a bit confusing but let me clear that up right now.
I have a class called UserController which has a method called updateUserData. It gets a Map<String, dynamic> and updates the given attributes of a user with whatever is given in the value of the map.
What I wanted to do is: Send a patch request to the server, wait for the server to return a changed user object, write that to some local variable and return either the value or the error to whoever called that method (which in my case is a GUI class).
The current method as it is:
Future<User> updateUserData(Map<String, dynamic> changes) async {
return await http.patch(
"url",
headers: {HttpHeaders.authorizationHeader: "token"},
body: changesMap
).then((newUserObject) => {
currentUser = newUserObject;
//return new user object for display
}); //error from server gets forwarded to GUI.
}
Sadly this doesn't work at all. Seems like Flutter/dart doesn't know what to return there (it gives me a return_of_invalid_type_from_closure error).
I hope it's clear what my goal was. I want to use a "then" clause in this method but then still return a future which either contains the user I get from the server or the error I get.
How do I do that? I looked up so many Future tutorials so far and none used something similar.
You never need to use async/await with then. In your case, the simplest thing to do is await the response of your request, and then, put it to your local variable.
Then you just need to return the value.
Future<User> updateUserData(Map<String, dynamic> changes) async {
final response = await http.patch(
"url",
headers: {HttpHeaders.authorizationHeader: "token"},
body: changesMap,
);
// You need to parse the response to get your User object.
final responseJson = json.decode(response.body);
newUserObject = User.fromJson(responseJson);
currentUser = newUserObject;
return newUserObject;
}
If you need to decode your Map to a Class, you can see the answer given here