Tizi Dev
Tizi Dev

Reputation: 311

Show an AlertDialog just for one time in flutter

Hy Guys. I have an alert dialog which starts automaticaly by initState but this AlertDialog has to be shown just one time for the user. this is my code:

@override
  void initState() {
    super.initState();
    Future.delayed(const Duration(milliseconds: 1000), () {
      showAlertDialogue();
    });
  }

  showAlertDialogue() {
    showDialog(
      context: context,
      child: InfoAlert(),//this is the AlertDialog from another file
    );
  }

any help to make this dialog just one time dialog?

Upvotes: 1

Views: 1637

Answers (1)

Amroun
Amroun

Reputation: 465

Add this to your dependencies:

shared_preferences: ^0.5.12+2

Add this import in your page:

import 'package:shared_preferences/shared_preferences.dart';

Update your code:

  @override
  void initState() {
    super.initState();
    SharedPreferences.getInstance().then((prefs) {
    final int dialogOpen = prefs.getInt('dialog_open') ?? 0;
    if (dialogOpen == 0) {//show dialog for one time only      
      Future.delayed(const Duration(milliseconds: 1000), () {
        showAlertDialogue();
        prefs.setInt("dialog_open", 1);
      });
    }
   });
  }

Upvotes: 3

Related Questions