How to show a popup on app start in Flutter

Viewed 7461

I want to add a popup on the app load (or let's say each time the user opens the app) in Flutter. Can anyone help me with that? I understand that I have to use the AlertDialog widget, but I can't find a proper condition to determine the app start trigger.

Any help is highly appreciated.

4 Answers

You can use Shared Preferences

When launching the app, get the value from shared pref (Ex: isFirstLoaded). If isFirstLoaded == true then show the dialog.

When the dialog is dismissed, set isFirstLoaded = false and save to shared preferences.

Below is an example (please note that the example doesn't handle the dismiss event when tapping on Back key).

Add shared_preferences to your pubspec.yaml

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(MyStatelessApp());
}

class MyStatelessApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Stateless Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: StatelessWidgetDemo(),
    );
  }
}

class StatelessWidgetDemo extends StatelessWidget {
  final keyIsFirstLoaded = 'is_first_loaded';

  @override
  Widget build(BuildContext context) {
    Future.delayed(Duration.zero, () => showDialogIfFirstLoaded(context));
    return SafeArea(
        child: Scaffold(
            appBar: AppBar(
              title: Text('Flutter Stateless Demo'),
            ),
            body: Center(
              child: Text('Hello'),
            )));
  }

  showDialogIfFirstLoaded(BuildContext context) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool isFirstLoaded = prefs.getBool(keyIsFirstLoaded);
    if (isFirstLoaded == null) {
      showDialog(
        context: context,
        builder: (BuildContext context) {
          // return object of type Dialog
          return AlertDialog(
            title: new Text("Title"),
            content: new Text("This is one time dialog"),
            actions: <Widget>[
              // usually buttons at the bottom of the dialog
              new FlatButton(
                child: new Text("Dismiss"),
                onPressed: () {
                  // Close the dialog
                  Navigator.of(context).pop();
                  prefs.setBool(keyIsFirstLoaded, false);
                },
              ),
            ],
          );
        },
      );
    }
  }

call your dailog inside initState method (from main or statup page):

  @override
  void initState() {
  WidgetsBinding.instance.addPostFrameCallback(_showOpenDialog);
  super.initState();
  }

  // show Open Dialog method
  _showOpenDialog(_) {
    showDialog(
        context: context,
        builder: (context) {
          return YourCustomDialog();
        });
  }
class MyWidget extends StatelessWidget {
  bool firstBuild = true;

  // show Open Dialog method
  _showOpenDialog(context) {
    showDialog(
        context: context,
        builder: (context) {
          return Dialog();
        });
  }

  @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (firstBuild) {
        firstBuild = false;
        _showOpenDialog(context);
      }
    });
    return Text('Hello, World!');
  }
}
Related