我正在尝试显示名为“年龄限制”的弹出窗口。我有一个 ageRestriction 变量,它带有一个字符串。当用户单击基于 ageRestriction 值的按钮时,我只希望显示一次弹出窗口:例如,如果 ageRestriction =“ 18”,则稍后显示为“ 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");
}
答案 0 :(得分:1)
您不应使用setAgeList,然后, 如果列表为空,则必须获得空列表
替换getAgeList;
var list = _prefs.getStringList("AgeList")??<String>[];
list.add(age);
return await _prefs.setStringList("AgeList", list);