Can some one help me to identify the issue in below piece of code
void main() async {
bool c =getstatus();
print(c);
}
Future<bool> getMockData() {
return Future.value(false);
}
bool getstatus() async
{
Future<bool> stringFuture = getMockData();
bool message = stringFuture;
return(message); // will print one on console.
}
To get values from a Future(async) method, you have to await them. And after await the variable you get is not a Future anymore. So basically your code should look like this:
void main() async {
bool c = await getstatus();
print(c);
}
Future<bool> getMockData() {
return Future.value(false);
}
Future<bool> getstatus() async {
bool message = await getMockData();
return message;
}
Future<bool> stringFuture = await getMockData();
an async method must return Future of something then in the main you have to get the bool value by writing await
void main() async {
bool c = await getstatus();
print(c); // will print false on the console.
}
Future<bool> getMockData() {
return Future.value(false);
}
Future<bool> getstatus() async {
Future<bool> stringFuture = await getMockData();
return stringFuture; // will return false.
}
Related
How do you check if an async void method is completed in Dart?
Method 1:
await voidFoo();
print("the above function was completed");
Future<void> voidFoo() async{
await Future.delayed(Duration(seconds:1));
}
Method 2:
Using a boolean variable like this,
bool isCompleted = false;
...
await voidFoo();
Future<void> voidFoo() async{
await Future.delayed(Duration(seconds:1));
isCompleted = true; //assuming isCompleted can be accessed here
}
There are too many methods to do this
i prefer to do this
Future<void> myFunction() async {
await Future.delayed(Duration(seconds: 3)); // your future operation
}
main() async {
await myFunction();
print("finished");
}
You can use dart Completer.
import 'dart:async';
void main() async {
final completer = Completer<String>();
Future<String> getHttpData()async{
return Future.delayed(const Duration(seconds: 1), () => "Future Result");
}
Future<String> asyncQuery()async {
final httpResponse = await getHttpData();
completer.complete(httpResponse);
return completer.future;
}
print('IsCompleted: ${completer.isCompleted}');
await asyncQuery();
print('IsCompleted: ${completer.isCompleted}');
}
Result;
IsCompleted: false
IsCompleted: true
I have this function that calls a Future<bool> function :
bool checkId(String id, context) {
bool ret;
checkMissingId(id, context).then((value) => ret = value);
return ret;
That calls :
Future<bool> checkMissingId(String id, context) async {
String str = id.toLowerCase();
String letter = str[0];
if (checkStr(id, letter, str) == false)
return false; //checks some rules on strings
else {
try {
var data = await FirebaseFirestore.instance
.collection("ids/tabs/" + letter)
.doc(str)
.get();
if (data.exists) {
return false;
} else
return true;
} catch (e) {
await showErrDialog(context, e.code);
return false;
}
}
}
ret returns null, not a bool value.
Edit : checkId must be of type bool, not Future<bool>
Because it is null when the checkId function returns. You should await the operation, like this:
Future<bool> checkId(String id, context) async {
bool ret = await checkMissingId(id, context);
return ret;
}
You need to pause the execution of the program for the checkMissingId method to complete before return the ret variable. You do this by using the await keyword and marking the function as async.
You should change the code to:
Future<bool> checkId(String id, context) async {
bool ret = await checkMissingId(id, context);
return ret;
}
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 want check if device is connected to internet or not and i done with class that do this work and return to me a bool value and i use from this class to other page and pass returned value to bool variable but get get this error that say Future<dynamic> is not a subtype of type bool in type cast
import 'dart:io';
class CheckConnection{
static Future<bool> checkConnection() async {
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
return (await checkConnection()) == true;
}
} on SocketException catch (_) {
print('not connected');
}
}
}
In place where you want to check you have to do like this:
CheckConnection.checkConnection().then((bool result){
/* check result here */
})
Or you can do this inside async function like checkConnection:
void _myFunction() async {
bool result = await CheckConnection.checkConnection();
/* check result here */
}
I don't get why you call checkConnection again inside for it (recursive effect). Are you sure you don't want to do like:
class CheckConnection {
static Future<bool> checkConnection() async {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
return true;
}
/* try catch also can be applied! */
return false;
}
}
Just return this
return await checkConnection();
Why can't I get results of listen2? How do I modify it?In the sample,I can only access the listen1 results but not the listen2 results。i am new
sample code:
Future<List<int>> getResult() async {
var a = creatDataToken();
var e= await Socket.connect(MyApp.host, MyApp.port).then((Socket socket) async{
socket.add(a);
socket.listen((List<int> listen1) async{
debugPrint('result listen1 :$listen1');
List<int> loginList= creatDataLogin(listen1);
await Socket.connect(MyApp.host, MyApp.port).then((Socket socket) async {
socket.add(loginList);
debugPrint('add:$loginList');
await socket.listen((List<int> listen2) {
debugPrint('result listen2 :$listen2');
return listen2;
});
});
});
});
enter image description here
bool flag;
Future getResult() async {
flag = false;
var a = creatDataToken() ;
var b= await Socket.connect(MyApp.host, MyApp.port).then((Socket socket){
mSocket=socket;
mSocket.add(a);
mSocket.addError((e){debugPrint('---addError--$e');});
mSocket.listen(onReceiver);
}).catchError((error){
debugPrint('---catchError--$error');
ToastUtils.showShortToast('username or password error!');
return;
});
return b;
}
void onReceiver(List<int> event) {
if(!flag){
debugPrint('result listen1 :$event');
flag=true;
List<int> loginList= creatDataLogin(event);
debugPrint('loginList:$loginList');
mSocket.add(loginList);
}else{
debugPrint('result listen2 :$event');
resolveResult(event);
}
}