flutter - 如何保持页面状态在颤动?
问题描述
我在 a 中有一个项目列表DragSelectGridView
,所以我想保留我选择的项目的状态。
假设我的应用程序中有 5 个页面,我使用pushReplacement
从第 1 页导航到第 2 页。第 2 页是我从中选择项目的位置,DragSelectGridView
然后我使用pushReplacement
第 3 页和从第 3 页导航到第 4 页。当我使用pushReplacement
返回页面导航时2 我选择的所有项目都已处置。
即使我关闭应用程序,我也想保持我在第 2 页中选择的项目的状态。
我已经尝试使用SharePrefrences
但我没有得到它..
这是我的代码:
class _IntresetState extends State<Intereset> {
final controller = DragSelectGridViewController();
final scrollcontrol = ScrollController();
@override
void initState() {
super.initState();
controller.addListener(scheduleRebuild);
}
@override
void dispose() {
controller.removeListener(scheduleRebuild);
super.dispose();
}
void scheduleRebuild() => setState(() {});
List<InterestModel> interestIn = [
InterestModel('assets/Art & Design.jpeg', 'Art & Design'),
InterestModel('assets/Tech.jpeg', 'Tech'),
InterestModel('assets/Food.jpeg', 'Food'),
InterestModel('assets/Animal.jpeg', 'Animal'),
InterestModel('assets/Fitness & Health.jpeg', 'Fitness & Health'),
InterestModel('assets/Car.jpeg', 'Car'),
InterestModel('assets/Sport.jpeg', 'Sport'),
InterestModel('assets/Book.jpeg', 'Book'),
InterestModel('assets/Game.jpeg', 'Game'),
InterestModel('assets/Film.jpeg', 'Film'),
InterestModel('assets/Travelling.jpeg', 'Travelling'),
InterestModel('assets/Tv & Music.jpeg', 'Tv & Music'),
InterestModel('assets/Dancing.jpeg', 'Dancing'),
InterestModel('assets/Cooking.jpeg', 'Cooking'),
InterestModel('assets/Learning.jpeg', 'Learning'),
InterestModel('assets/Pet.jpeg', 'Pet'),
InterestModel('assets/Politics.jpeg', 'Politics'),
InterestModel('assets/Photography.jpeg', 'Photography')
];
@override
Widget build(BuildContext context) {
return ProgressHUD(
child: Builder(
builder: (context) => Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.transparent,
leading: Container(),
actions: [
GestureDetector(
onTap: () async {
final progress = ProgressHUD.of(context);
progress?.show();
final getLength = controller.value.selectedIndexes
.map((e) => interestIn[e].name)
.toList();
if (getLength.length <= 0) {
print(getLength.length);
progress?.dismiss();
await Flushbar(
title: 'Ops!',
message: 'Select one Interest !!!',
duration: Duration(seconds: 3),
).show(context);
} else {
SharedPreferences pref =
await SharedPreferences.getInstance();
await pref.setBool('interest', true);
await firestore
.collection('interest')
.doc(auth.currentUser?.uid)
.set({'Interest': getLength}).then(
(value) => Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (_) => Done(),
),
),
);
progress?.dismiss();
}
},
child: Container(
height: 40,
width: 40,
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: LinearGradient(
colors: [
Constants.color1,
Constants.color2,
],
),
),
child: Center(
child: Icon(
Icons.check_outlined,
size: 18,
color: Colors.white,
)),
),
),
SizedBox(
width: 20,
),
],
),
extendBodyBehindAppBar: true,
body: SafeArea(
minimum: EdgeInsets.all(10.0),
child: Container(
height: double.infinity,
width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 10.0),
child: Text('Select Interests',
style: GoogleFonts.raleway(
textStyle: TextStyle(
color: Theme.of(context).primaryColor,
fontSize: 30,
fontWeight: FontWeight.bold,
),
)),
),
Expanded(
child: DragSelectGridView(
shrinkWrap: false,
scrollController: scrollcontrol,
triggerSelectionOnTap: true,
gridController: controller,
itemCount: interestIn.length,
gridDelegate:
new SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3, childAspectRatio: 0.7),
itemBuilder:
(BuildContext context, int index, isSelected) {
return Stack(
children: [
Padding(
padding: const EdgeInsets.all(4.0),
child: GestureDetector(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topRight: Radius.circular(40),
bottomLeft: Radius.circular(40),
),
image: DecorationImage(
image:
AssetImage(interestIn[index].url),
fit: BoxFit.fill,
colorFilter: ColorFilter.mode(
Colors.red, BlendMode.darken),
),
),
height: 180,
width: 200,
child: Padding(
padding: const EdgeInsets.only(
left: 25.0, bottom: 10),
child: Center(
child: Align(
alignment: Alignment.bottomLeft,
child: Text(
interestIn[index].name,
style: TextStyle(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.w500,
),
),
),
),
),
),
),
),
isSelected
? Positioned(
height: 60,
left: 90,
child: Container(
height: 30,
width: 30,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.white,
),
child: Center(
child: Icon(
Icons.check_outlined,
size: 18,
color: Colors.red,
),
),
),
)
: Container()
],
);
}),
这是我的代码的结果.....
解决方案
这是我会做的
在InterestModel
,我创建属性isSelected
然后方法.toJson()
和工厂方法InterestModel.fromJson(Map json)
(json序列化)
每次用户选择. InterestModel
_isSelected
SharedPreference
jsonEncode(interestIn)
如果我想检索列表,请解码字符串,jsonDecode(yourString)
然后对其进行迭代并应用InterestModel.fromJson(iteratedString)
代码示例(我没有尝试过):
兴趣模型类
class InterestModel {
String assetUrl;
String name;
bool isSelected;
InterestModel({this.assetUrl, this.name, this.isSelected});
Map toJson() {
return {
"assetUrl": assetUrl,
"name": name,
"isSelected": isSelected
};
}
factory InterestModel.fromJson(Map json) {
return InterestModel(
assetUrl: json["assetUrl"],
name: json["name"],
isSelected: json["isSelected"]
);
}
}
要将其保存到 SharedPreference 中,请确保更新列表值
Future<List<InterestModel>> retrieveInterests() async {
SharedPreferences pref = await SharedPreferences.getInstance();
String interestString = await pref.getString("interest_list");
List jsonArray = jsonDecode(interestString);
List<InterestModel> interests = [];
for (json in jsonArray) {
interests.add(InterestModel.fromJson(json));
}
return interests;
}
Future<void> saveToSharedPref(List<InterestModel> interests) async {
SharedPreferences pref = await SharedPreferences.getInstance();
await pref.setString("interest_list", jsonEncode(interests));
}
推荐阅读
- amazon-web-services - AWS S3 地理位置重定向
- php - 开启深色模式时更改 Facebook 评论框的配色方案
- c# - System.Net,无法解析符号“Net”
- python - 我如何使用 django ModelForm 对象和 Queryset 来做登录认证功能
- html - 允许用户发布 http/https 以外的 url 方案?
- php - 根据 Woocommerce 中的用户角色自定义客户新帐户邮件
- python - 为什么 Python Flask 应用程序仅在第二次重启后才呈现?
- node.js - 无法在 mongoose 中使用通用模型:“x”类型的参数不可分配给 MongooseFilterQuery 类型的参数
- here-api - /transit/Departures v8 缺少 APIKey 身份验证
- c - 如果我想长时间运行程序,如何忽略 SIGXCPU 信号?