所以我花了很长时间试图找到一个我认为是一个相当简单的问题的答案,但我找不到任何关于如何做到这一点的信息:
我有一个 Dog 类:
class UserDog extends UserAnimal{
Set<String> breeds = {};
UserDog(User? user) : super(user);
Future SetBreeds({ Set<String>? breeds }) async{
if (IsSignedIn() && breeds != this.breeds && breeds != null) {
Set<String> breedList = {};
for (var breed in breeds.where((b) => b != "")){ breedList.add(breed); }
await GetUserData().update({DatabaseConsts.BreedField: breedList.toList()});
this.breeds = breedList;
}
}
}
这个简单的类有一个字段,它用一堆其他字段扩展了一个超类,但我有兴趣在用户添加或删除小部件树中的品种时更新品种集。
由于我使用的是 hooks riverpod,因此我可以通过在 a中使用 aStateNotifier
和 a来让我的应用程序中的其他小部件重新构建良好。ref.watch()
HookConsumerWidget
但是当我有一个像对象这样的UserDog
对象并且当我调用该方法时只有一个字段被更改时,我的问题就出现了SetBreed()
,并且由于状态通知器只会在整个对象引用被更改后重建,这显然不会做任何事情。
HookConsumerWidget
那么,当通知程序中的对象字段而不是整个对象发生更改时,有没有一种方法可以重建?作为参考,这是当前的小部件代码:
class BreedTag extends HookConsumerWidget{
String text;
BreedTag(this.text);
@override
Widget build(BuildContext context, WidgetRef ref){
List<Widget> widgets = [];
var user = ref.watch(userProfile.state).state
if (text == ""){
widgets = const [
Icon(Icons.add),
SizedBox(child: Text("Add A Breed", overflow: TextOverflow.clip)),
];
}
else{
widgets = [
Expanded(
child: Align(
alignment: Alignment.center,
child: Text(
text,
overflow: TextOverflow.clip,
textAlign: TextAlign.center,
)
)
)
];
}
return Flexible(
flex: 20,
child: Flex(
direction: Axis.horizontal,
children: [
Expanded(
child: Container(
height: UserPageUIConsts.DataRowHeight,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(UserPageUIConsts.DataRowHeight/2),
color: Colors.amber
),
child: ClipRRect(
borderRadius: BorderRadius.circular(UserPageUIConsts.DataRowHeight/2),
child: MaterialButton(
// Remove this breed from the list if the tag is tapped
onPressed: () => user.SetBreeds(user.breeds.where((u) => u != breed).toSet()),
splashColor: Colors.blue,
padding: const EdgeInsets.all(0),
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: widgets,
)
),
),
)
)
)
],
),
);
}
}
提前致谢!