Reputation: 46
I am creating a simple loading screen between two screens in which I load it until task is not completed but I am stuck only on loading screen.
Navigator.of(context).pushReplacementNamed('/loading');
doTask(context);
void doTask(BuildContext context){
Navigator.of(context).pushReplacementNamed('/secondScreen');
}
Upvotes: 1
Views: 539
Reputation: 994
I would suggest using a future builder instead:
class SecondRoute extends StatelessWidget {
@override
Widget build(context) {
return Scaffold(
appBar: AppBar(),
body: FutureBuilder(
future: doTask(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Loading();
}
return SecondScreen();
}),
);
}
Future<void> doTask() async {
// Any future process here
await Future.delayed(
Duration(seconds: 3),
);
}
}
Upvotes: 1
Reputation: 2393
doTask won't be called, the code does not work after Navigator.of(context).push()
. Try completing task in loading screen, it is better you do your task in second screen and show loading while task is not complete.
class SecondRoute extends StatelessWidget {
Future<void> doTask() async {
//Dummy Code, Replace it with your task
await Future.delayed(
Duration(seconds: 2),
);
}
@override
Widget build(context) {
return Scaffold(
appBar: AppBar(),
body: FutureBuilder(
future: doTask(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
}
return Container(); //Replace it with your widget
}),
);
}
}
Upvotes: 0