I am doing dart with postgresql , I can't return data the conn.query(rows). but the results are coming ,how to return it, simple code is
main(){
someOtherFunc();
}
Future add() async{
var uri = 'postgres://postgres:root#localhost:5432/testdb';
var conn = await connect(uri);
var sql = 'select * from test';
return conn.query(sql).toList();
}
Future someOtherFunc() async {
print(await add());
}
I got return as "Instance of '_Future'!"
If you use await in the function you call add() from, you get the desired result
Future add() async {
var uri = 'postgres://postgres:root#localhost:5432/testdb';
var conn = await connect(uri);
var sql = 'select * from test';
return conn.query(sql).toList();
}
Future someOtherFunc() async {
print(await add());
}
async is contagious. When you call an async function, you can't return to sync execution. Everything that depends on the async results, needs to use await (or the "old" .then((value) {})) . async + await just create the illusion of sync execution.
Related
I have this piece of code
Future<List<RoomModel>> getTeacherRooms(String email) async {
var docs = await _roomRepo.getTeacherRooms(email);
List<RoomModel> rooms = [];
docs.map((doc) async {
var room = await toRoom(doc);
rooms.add(room);
}).toList();
return rooms;
}
I need to wait for toRoom() to return a value then put it in rooms
the problem is with this code is that rooms is returned empty
I just used "pskink" answer to solve this problem
this is the code
Future<List<RoomModel>> getTeacherRooms(String email) async {
var docs = await _roomRepo.getTeacherRooms(email);
return await Future.wait(docs.map((doc) => toRoom(doc)).toList());
}
How can i return a string from a future function?
Future<String> functionA() async {
var x = await fetchX();
return x;
}
Future<String> fetchX() {
return Future.delayed(Duration(seconds: 4), () => 'example');
}
Future<String> la() async {
print(await functionA()); //this works correctly
return await functionA(); //this return always an instance of Future
}
How can i return "example" from the future function, there is a method to do it, and where is my error?
Future<String> fetch() async {
return
http.get('url')
.then((response) => response.body);
}
That way you can sneak a .catchError into there. :)
You need to specify what your function will return. All you have to do is add Future to the beginning of the method.
Future<String> fetch() async {
final response = await http.get('url');
String conteggio = response.body;
return conteggio;
}
And you have to do this in a method. You can only assign constant values in fields other than methods.
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().
I have a flutter web where i have a JavaScript function like this:
async function doSomething(value) {
let x = await something(x);
return x
}
When I'm now in dart, I have:
final result = await js.context.callMethod('doSomething', ['someValue']));
This returns [object Promise] when I print it, but it does ignore await, does not have a .then function and is therefore not working with promiseToFuture either.
How can I wait for JavaScript to be executed?
Just await doesn't work for js.context.callMethod.
This must be added somewhere in your code, maybe like javascript_controller.dart
#JS()
library script.js;
import 'package:js/js.dart';
import 'dart:js_util';
#JS()
external dynamic doSomething();
and then
Future getSomething(String someValue) async {
var result = await promiseToFuture(doSomething());
return result;
}
Maybe use a Future builder to wait for JS to execute?
Future getSomething(String someValue) async {
var result = await js.context.callMethod('doSomething', [someValue]));
return result;
}
FutureBuilder(
future: getSomething(someValue),
builder: (context, snapshot) {
if (snapshot.hasData) {
var data = snapshot.data;
print(data);
} else {
return Loading();
}
});
Place it in index.html
<script src="script.js" defer></script>
In Script.js
async function showAlert(href,hashtag,quote) {
if (response) {
window.dartFunc("asd");
dartFunc("asd");
} else if () {
alert("error adding points");
}
else{
alert("error dialog close");
}
});
};
In your dart file in initstate()
setProperty(window, 'dartFunc', js.allowInterop(dartFunc));
sss() async {
await js.context.callMethod('showAlert', [
'',
'',
''
]);
}
String dartFunc(String str) {
Common.showToast('Music');
Common.showToast(str);
return 'Inside dartFunc: ' + str;
}
I tried the same method to do asynchronously from js file using async and used --promisetofuture in dart file but i am unable to wait until we get response from js file for flutter web
async function getPhoneNumber() {
let res = await someFunction to wait for someTime;
return res;
}
function somfunc() async{
var number = await
promiseToFuture(js.context.callMethod('getPhoneNumber'));
}
I want to call function2 after function1 finished.
To do that I did like that.
this is function 1.
Future _uploadImages() async {
setState(() {isUploading = true;});
images.forEach((image) async {
await image.requestThumbnail(300, 300).then((_) async {
final int date = DateTime.now().millisecondsSinceEpoch;
final String storageId = '$date$uid';
final StorageReference ref =
FirebaseStorage.instance.ref().child('images').child(storageId);
final file = image.thumbData.buffer.asUint8List();
StorageUploadTask uploadTask = ref.putData(file);
Uri downloadUrl = (await uploadTask.future).downloadUrl;
final String url = downloadUrl.toString();
imageUrls.add(url);
});
});
}
this is function 2
Future _writeImageInfo() async {
await _uploadImages().then((_) async {
await Firestore.instance.collection('post').document(uid).setData({
'imageUrls': imageUrls,
}).then((_) {
Navigator.of(context).pop();
});
}
But console says function2's imageUrls called when list length = 0 because it's called before function 1 finished.
I don't know why that function not called after function 1.
How can I make this right?
This happens because of your images.forEach. The .forEach doesn't work with async callback. Therefore it doesn't wait the end of each the foreach to continue the function.
In general, don't use .forEach in dart anyway. Dart did a great job on the for keyword directly.
So ultimately, you should do the following:
for (final image in images) {
...
}