2

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.

W. Kabir
  • 89
  • 1
  • 3
  • 11

4 Answers4

5

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);
                },
              ),
            ],
          );
        },
      );
    }
  }

Tushar Patil
  • 748
  • 4
  • 13
  • But I don't want to show the popup every time the page is built. I want to show it once when the app starts. – W. Kabir Jun 23 '20 at 14:49
  • For my next app run I can't see the popup. – W. Kabir Jun 23 '20 at 16:57
  • That's what you wanted right? if not then you would have to reset the instance of the shared preferences when you open the app, so it will be invoked only once – Tushar Patil Jun 25 '20 at 14:32
  • Got deprecation warnings: `/Applications/flutter/.pub-cache/hosted/pub.flutter-io.cn/shared_preferences-0.5.12+4/android/src/main/java/io/flutter/plugins/sharedpreferences/MethodCallHandlerImpl.java:9: warning: [deprecation] AsyncTask in android.os has been deprecated`, with my setup: `Flutter (Channel dev, 1.26.0-12.0.pre, on Mac OS X 10.15.7 19H15 darwin-x64, locale en-CN)` – kakyo Mar 08 '21 at 03:00
0

There are many options to make a dialog or something else.

You can use Alert Dialog, Dialog Awesome, and more.

But if you want to make your custom dialog or something like that then you can use Overlay Widget.

Check the link: https://api.flutter.dev/flutter/widgets/OverlayEntry-class.html

also tutorial: https://www.youtube.com/watch?v=A3co3Tskjtg

Hasib Akon
  • 580
  • 6
  • 16
0

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();
        });
  }
Omer Gamliel
  • 456
  • 3
  • 6
  • Will it not load each time I navigate to the widget! What I want a one time result, i.e. a user sees a popup when he/see loads the app, he/she will again see on his/her next visit. I hope I am clear. – W. Kabir Jun 23 '20 at 14:40
0
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!');
  }
}
Prathik
  • 474
  • 3
  • 13