带有条件的 Flutter 显示弹出窗口

Flutter display pop-up with condition

我正在尝试显示名为“年龄限制”的弹出窗口。我有一个变量 ageRestriction,它接受一个字符串。当用户基于 ageRestriction 的值单击按钮时,我只想显示一次弹出窗口 ex: If ageRestriction = "18" display once if稍后它变为“20”再次显示它,所以当“18”再次出现时它想要显示。 我试图将它保存到共享首选项列表,然后检查该值是否存在于列表中。但是没有用

这是我目前试过的代码

// Defining variables
String ageRestriction;
List<String> storedAges;


//Button with pop-up and conditions
     InkWell(
            onTap: () {
       onTap: () {
              if(widget.ageRestriction != null && widget.ageRestriction.isNotEmpty){
                storedAges.contains(widget.ageRestriction) ? widget.onPressed():
                AwesomeDialog(
                  popContext: false,
                  context: context,
                  dialogType: DialogType.WARNING,
                  animType: AnimType.TOPSLIDE,
                  btnOkText: S.of(context).yes,
                  body:  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text(S.of(context).are_you_18(widget.ageRestriction),style:  TextStyle(
                          fontSize: 16,
                          fontFamily: "Montserrat",
                          fontWeight: FontWeight.bold),),
                    ],
                  ),
                  btnOkOnPress: () async{
                    setState(() {
                      SharedPreferencesHelper().addToAgeList(widget.ageRestriction);
                      storedAges = SharedPreferencesHelper().getAgeList();
                      print("Widget stored" + storedAges.length.toString());
                    });
                    ///Working Code
                   // SharedPreferencesHelper().setAgeData = widget.ageRestriction;
                    widget.onPressed();
                    Navigator.of(context).pop();
                  },
                  btnCancelOnPress: () {
                  //  Navigator.pop(context);
                  },
                  btnCancelText: S.current.no,
                  btnOkColor: Theme.of(context).accentColor,
                  btnCancelColor: Color(0xFF084457).withOpacity(0.9),
                ).show();
                setState(() {
                  saveAgeData = widget.ageRestriction;
                });
              }else {
                widget.onPressed();
              }
            },
           }),




//Shared preference functions
  Future<bool> setAgeList(String age) async {
    return await _prefs.setStringList("AgeList", [age]);
  }

  Future<bool> addToAgeList(String age) async {
    return await _prefs.setStringList("AgeList", _prefs.getStringList("AgeList")..add(age));
  }

  List<String> getAgeList() {
    return _prefs.getStringList("AgeList");
  }

你不应该使用 setAgeList 然后, 如果列表为空,则必须得到空列表

替换getAgeList;

var list = _prefs.getStringList("AgeList")??<String>[];
list.add(age);
return await _prefs.setStringList("AgeList", list);