1

My app doesn’t require to load anything but I want to give it a 2 second loading screen for visual perpose. How do I do it?

yearat
  • 33
  • 6

1 Answers1

1

Create a DummyPage widget, which will take you to the YourHomePage (primary widget of your app) after 2 seconds.

Update: I used Timer earlier but it would require to import extra library, you can instead use Future.delayed as suggested by @anmol.majhail

void main() {
  runApp(MaterialApp(home: DummyPage()));
}

class DummyPage extends StatefulWidget {
  @override
  _DummyPageState createState() => _DummyPageState();
}

class _DummyPageState extends State<DummyPage> {
  @override
  void initState() {
    super.initState();
    // here is the logic 
    Future.delayed(Duration(seconds: 2)).then((__) {
      Navigator.push(context, MaterialPageRoute(builder: (_) => YourHomePage()));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(); // this widget stays here for 2 seconds, you can show your app logo here
  }
}
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
  • As Timer class need to import `import 'dart:async';`, Another Way could be using - `Future.delayed` - simple & no import - `Future.delayed(Duration(seconds: 2), () { Navigator.push( context, MaterialPageRoute(builder: (_) => YourHomePage())); });` – anmol.majhail Sep 02 '19 at 18:45
  • Yes, you can do that with `Future.delayed` too. – CopsOnRoad Sep 02 '19 at 18:47
  • Feel free to update you answer :) – anmol.majhail Sep 02 '19 at 18:47
  • But where would you want to use that, inside `main()`? – CopsOnRoad Sep 02 '19 at 18:48
  • no , same place where you have timer - `Timer(Duration(seconds: 2), () { Navigator.push(context, MaterialPageRoute(builder: (_) => YourHomePage())); });` with `Future.delayed(Duration(seconds: 2), () { Navigator.push( context, MaterialPageRoute(builder: (_) => YourHomePage())); });` – anmol.majhail Sep 02 '19 at 18:49
  • 1
    Ahh, I didn't notice you used `then`, it's difficult to read code in comment, I just read you saying use `Future.delayed` and I thought of using `await`. Let me update the answer now – CopsOnRoad Sep 02 '19 at 18:50
  • @anmol.majhail And I wasn't much aware of different classes getting imported from different package. – CopsOnRoad Sep 02 '19 at 18:54