This question already has answers here:
What is a Future and how do I use it?
(6 answers)
Closed 2 years ago.
I am trying to convert the response from api to string in flutter. I am still a beginner to Flutter so I'm sorry about that.
Whenever I do the get and assign it to a variable, the value is always 'Instance of Future' rather than the actual text? So does this mean I have to convert it to text?
This is the code that I used.
gethttps() async{
var response = await http.get(url);
print("JSON" + response.body);
String data = response.body;
data = json.decode(response.body.toString());
return data;
}
CALL FROM OUTSIDE THE FUNCTION
var response = gethttps();
you can follow the link : https://stackoverflow.com/a/50296350/6413387
Basically you have two options
gethttps().then((result) {
print(result);
setState(() {
someVal = result;
})
})
or
funcThatMakesAsyncCall() async {
String result = await gethttps();
print(result);
setState(() {
someVal = result;
})
}
You can change signature of function to this one
Future<String> gethttps() async{....}
and then use
var data=await gethttps();
user await
Related
This question already has answers here:
What is a Future and how do I use it?
(6 answers)
Closed 10 months ago.
I don't understand how to lead to one type
my function:
Future<String> getToken(String login) async {
final data = await (select(authInfos)
..where((tbl) => tbl.login.equals(login)))
.getSingle();
return data.token;
}
row with error:
String token = myDatabase.authInfosDao.getToken(login);
For functions that returns a future result you will need to put await on calling it to ensure that the variable will get the return of the said function.
Here's the Syntax:
String token = await myDatabase.authInfosDao.getToken(login);
Update:
Future<void> initState() async {
// TODO: implement initState
String token = await myDatabase.authInfosDao.getToken(login);
super.initState();
}
Note: When using await expression it should be used on an async funtion.
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
I've fetched a json object and deserialized it and then returned it too.
I want to use this in another file.
I'm unable to assign the values that I'm getting in the first step.
Here are all the codes...
Service
Future getGeoPoints(String accessToken, String tripId) async {
String requestUrl;
var response = await get(
Uri.parse(requestUrl),
headers: {
'Authorization': "Bearer $accessToken",
},
);
if (response.statusCode == 200) {
Map<String, dynamic> responseBody = json.decode(response.body);
GetGeoPoints geoPoints = GetGeoPoints.fromJson(responseBody);
List listOfGeoPoints = [];
for (var geoPoint in geoPoints.geoPoints) {
listOfGeoPoints.add(
{
'latitude': geoPoint.latitude,
'longitude': geoPoint.longitude,
'timestamp': geoPoint.timeStamp,
},
);
}
// print('List of geo points: ' + '$listOfGeoPoints');
return listOfGeoPoints;
} else {
throw Exception('Failed to load data from server');
}
}
File where I need the above values
List routeCoordinates;
Future<void> getValues() async {
getGeoPoints(widget.accessToken, widget.tripId)
.then((value) => routeCoordinates = value);
}
When I run the app, routeCoordinates is null but when I hotreload, it contains the value.
I want to have the values as soon as the screen starts. What is the right way to assign the values here?
I've also tried this:
routeCoordinates = getGeoPoints...
It throws error..
Please help.. Thanks..
The function getGeoPoints() is an asynchronous one. But on the other file, you are not using the await keyword, instead you are using then(). So your code is not waiting for that function to return value.
Try using below code,
List routeCoordinates;
Future<void> getValues() async {
routeCoordinates = await getGeoPoints(widget.accessToken, widget.tripId);
}
Let us know how it went.
You need to use a FutureBuilder to define a behaviour depending on the state of the request. You'll be able to tell the widget what to return while your app is waiting for the response to your request. You can also return a specific widget if you get an error(if your user is offline, for example).
Edit: I've linked the official docs but give this article a read if it's not clear enough.
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);
}
This question already has answers here:
What is a Future and how do I use it?
(6 answers)
Closed 2 years ago.
What i am trying to do is i am fetching profile from fetchUser.But i don't know any other way that i can pull http data other than string.
class FollowingUserModel {
final String id;
final String author;
User profile;
final String profileid;
FollowingUserModel({this.id, this.profileid, this.author, this.profile}) { profile = fetchUser() as User; }
Future<User> fetchUser() async{
final response = await http.get("$SERVER_IP/api/users/$profileid/?format=json");
if (response.statusCode == 200) {
var responseJson = json.decode(response.body);
return User.fromJSON(responseJson);}}
factory FollowingUserModel.fromJSON(Map<String, dynamic> jsonMap) {
return FollowingUserModel(
id: jsonMap['id'] as String,
author: jsonMap['author'] as String,
profileid: jsonMap['profile'] as String,
);}}
Does anybody know how to do it?
Just create an asynchronous function .
If you have Future<User>, to convert it to User, you need to add await; and to use await, you need to add async:
Future<void> test() async {
User user = await fetchUser();
}
You can learn more about asynchronous function here
From where you are calling do this,
User user = await followingUserModel.fetchUser();
Future<User> means it will return an User object by asynchronously(in future), so make the call with await, then your code will wait till it get the return.