Kucing Malaya
Kucing Malaya

Reputation: 465

Is there a way to skip await if it's too long? (Flutter)

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.

Upvotes: 5

Views: 1113

Answers (2)

Rafat Rashid Rahi
Rafat Rashid Rahi

Reputation: 629

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

Upvotes: 4

Dipak Prajapati
Dipak Prajapati

Reputation: 390

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

Upvotes: 3

Related Questions