Home > Blockchain >  How can i "sleep" in flutter and wait to run something
How can i "sleep" in flutter and wait to run something

Time:02-08

I'm coding my first app in flutter, so i want to show a WelcomeDialog at the first 5 seconds when user has loged in. How can i do that?

i've implemented this code inside class _HomeScreenState extends State<HomeScreen> , but it doesnt shows nothing at the 5 seconds of loged in.

  //at 5 seconds to loged in, welcome dialog appear on the screen
  Future<void> startDialogWelcome() async {
    await Future.delayed(const Duration(seconds: 5), () {
      _showDialogWelcome(context);
    });
  }

enter image description here

CodePudding user response:

I've created an example for you. You can use initState method with override. You can simply use the showDialog API to show a dialog on the screen also You can use the AlertDialog widget inside the dialog body.

If you want test: https://dartpad.dev/684308e16c95834e35f1e22d5e75e05e


class HomeScreen extends StatefulWidget {
  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  
  @override
  void initState() {
    startDialogWelcome();
    super.initState();
  }
  
  Future<void> startDialogWelcome() async {
    await Future.delayed(const Duration(seconds: 5), () {
      _showDialogWelcome();
    });
  }
  
  void _showDialogWelcome() {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('Welcome!'),
            content: Text('Hey! Welcome to my app!')
          );
        });
  }

  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(
          'Hello, World!',
          style: Theme.of(context).textTheme.headline4,
        ),
      ),
    );
  }
}
  •  Tags:  
  • Related