flutter - 调用 setState 时提供程序自动更新
问题描述
我是 Flutter 的新手,目前正在与 Providers 合作。我正在从 api 中提取一些静态数组列表并将其保存到提供程序。我让用户从此列表中选择并附加到他使用表单创建的项目。
因此,每次用户尝试创建新项目时,他/她都应该看到选择设置为 false 的静态列表。
但是,提供者数组变量会在调用 setState 时自动更新。以下是我面临的问题..
主要.dart
MultiProvider(
providers: [
ChangeNotifierProvider<Info1Class>(
create: (ctx) => Info1Class(),
),
ChangeNotifierProvider<Info2Class>(
create: (ctx) => Info1Class(),
),
],
child: MaterialApp(
在我的有状态小部件中的构建方法中。我得到这样的提供者详细信息。
screenArray.clear();
final t = Provider.of<Info1Class>(context, listen: false).dataArray;
screenArray.addAll(t);
每当我调用 setState 来更新 screenArray 的元素时,提供程序数据也会得到更新。
setState(() {screenArray[0].selected = true})
在 setState() 之后,如果我打印 Provider dataArray 的第一个元素,它会显示为 true。
print(Provider.of<Info1Class>(context, listen: false).dataArray[0].selected)
我的依赖
provider: ^4.3.2+4
有没有办法避免 Provider 数据被更新而只更新我的 Stateful Widget 中的变量?
如果我遗漏了什么,请告诉我。谢谢您的帮助。
解决方案
我为这个问题尝试了 Getx 和 Provider,这是引用对象而不是 Provider 或 GetX 的问题,我正在应对对象、列表或所有数据的引用。为了解决这个问题,我创建了每个对象的克隆然后使用它。
// COMMON
String? uid;
String? username;
String? fullName;
String? email;
num? timestamp;
List<ProfilePhoto>? photos;
List<String>? skills;
我添加了一个对象列表和其他简单的字符串列表克隆类
MyUser.clone(MyUser? myUser) {
uid = myUser?.uid;
username = myUser?.username;
fullName = myUser?.fullName;
userType = myUser?.userType;
email = myUser?.email;
timestamp = myUser?.timestamp;
photos = ProfilePhoto.cloneList(myUser?.photos);
status = myUser?.status;
skills = [...(myUser?.skills ?? [])];
}
构造函数
MyUser({
this.uid,
this.username,
this.fullName,
this.email,
this.timestamp,
this.photos,
this.skills,)};
摄影课
class ProfilePhoto {
String? id;
String? title;
String? url;
File? file;
bool? isDefault;
ProfilePhoto({
this.id,
this.title,
this.url,
this.file,
this.isDefault,
});
ProfilePhoto.clone(ProfilePhoto profilePhoto) {
id = profilePhoto.id;
title = profilePhoto.title;
url = profilePhoto.url;
file = profilePhoto.file;
isDefault = profilePhoto.isDefault;
}
static List<ProfilePhoto>? cloneList(List<ProfilePhoto>? items) {
if (items == null) return [];
List<ProfilePhoto>? newItems = [];
for (ProfilePhoto item in items) {
newItems.add(ProfilePhoto.clone(item));
}
return newItems;
}
}
屏幕布局
@override
void didChangeDependencies() {
super.didChangeDependencies();
final data = _userController.user;
MyUser? user = MyUser.clone(data);
}
void _onChangeDefault(int index) {
ProfilePhoto pp = _profilePhotos[index];
setState(() {
_profilePhotos.removeAt(index);
_profilePhotos.insert(0, pp);
});
}
这可能不是一个好的或优化的解决方案,但这解决了我在状态管理器中自动更新数据的问题
推荐阅读
- javascript - 初学者问题:(可选)promise 结合箭头/访问结果/错误值
- pipe - Bazel 构建命令模棱两可的标准输出/标准错误,而管道
- r - 获取一个欠定系统的 n 个解的样本
- android - SD 卡保护 - 按键访问
- swift - SwiftUI 下 TabView 是如何实现的
- jquery - jQuery/Thymeleaf - 设置选中的值
- javascript - Beautifulsoup 抓取 javascript 表问题 csv
- python - 使用 Seaborn FacetGrid 时的 Figuresize
- angular - 使用哪种技术来更新视口中的数千个元素(如 flightradar24.com)并具有良好的性能?
- xamarin - 如何在 Xamarin 中为相同的自定义字体添加多个字体文件