I use async await in main so the user has to wait in the splash screen before entering the app.
void main() async {
await Firebase.initializeApp();
String? x;
await FirebaseDatabase.instance.ref().child("data").once().then((snapshot) {
Map data = snapshot.snapshot.value as Map;
x = jsonEncode(data);
});
return ChangeNotifierProvider<DataModel>.value(
value: DataModel(data: x),
child: MaterialApp()
);
}
If there are users entering the app without an internet connection, they will be stuck on the splash screen forever. If there are also users with slow internet connection, they will be stuck on the splash screen longer.
So no matter what the internet connection problem is, I want to set a maximum of 5 seconds only to be in the await, if it exceeds, skip that part and go straight into the app.
CodePudding user response:
You can use the timeout method on the Future
class.
You can pass a Duration
, and an onTimeout
callback which will be called if the duration of time has been exceeded.
CodePudding user response:
Pass your Firebase api call to a function, make the method return future,
Future<String?> getData() async {
await FirebaseDatabase.instance.ref().child("data").once().then((snapshot) {
Map data = snapshot.snapshot.value as Map;
return jsonEncode(data);
});
}
Then on main method, attach a timeout with that method you created
void main() async {
await Firebase.initializeApp();
String? x = await getData().timeout(Duration(seconds: 5), onTimeout: () {
return null };
return ChangeNotifierProvider<DataModel>.value(
value: DataModel(data: x),
child: MaterialApp()
);
}
So if you api takes more then 5 seconds of time, then it exit and return null
CodePudding user response:
you can User Race condition or Future.timeout
Race condition using future.any
final result = await Future.any([
YourFunction(),
Future.delayed(const Duration(seconds: 3))
]);
in above code one who finish first will give result, so if your code takes more than 3 sec than other function will return answer