首页 > 解决方案 > 在颤动中只显示一次 AlertDialog

问题描述

嗨伙计们。我有一个由 initState 自动启动的警报对话框,但是这个 AlertDialog 必须只为用户显示一次。这是我的代码:

@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
    );
  }

有什么帮助可以使这个对话只是一次对话吗?

标签: flutter

解决方案


将此添加到您的依赖项中:

shared_preferences: ^0.5.12+2

在您的页面中添加此导入:

import 'package:shared_preferences/shared_preferences.dart';

更新您的代码:

  @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);
      });
    }
   });
  }

推荐阅读