You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter Provider中仅当特定参数变更时获取完整值

解决方案

要实现仅当LocationModel的city字段变化时获取完整的LocationModel对象,你可以调整context.select的用法:让它以city作为依赖判断依据,但返回整个LocationModel实例。

具体代码修改

@override
Widget build(BuildContext context) {
  LocationModel? locationModel = context.select((LocationModel? model) {
    // 以city字段作为依赖判定条件,仅当city变化时返回完整model
    return model;
  }, (model) => model?.city);

  // 后续可直接使用完整的locationModel对象
  String city = locationModel?.city ?? '';
  String street = locationModel?.street ?? '';
  // ...其他字段的业务逻辑处理
}

关键注意事项

  • 确保LocationModel正确实现==运算符和hashCode方法,Provider依赖对象的相等性判断来确定是否触发更新。示例实现如下:
class LocationModel {
  final String? city;
  final String? street;
  final String? country;

  LocationModel({this.city, this.street, this.country});

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is LocationModel &&
          runtimeType == other.runtimeType &&
          city == other.city &&
          street == other.street &&
          country == other.country;

  @override
  int get hashCode => city.hashCode ^ street.hashCode ^ country.hashCode;
}

如果仅需关注city的变化,也可以在==和hashCode中只包含city字段,但这会忽略其他字段的变更,需根据实际业务需求选择。

内容的提问来源于stack exchange,提问作者Katelyn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 13:15:34