向 Flutter Riverpod StreamProvider 传递参数

Pass parameters to Flutter Riverpod StreamProvider

我正在尝试将相同的参数传递给 StreamProvider,但我无法让它工作,这段代码工作得很好

 final dataStreamProvider = StreamProvider.autoDispose<DataModel>((ref) {
      return Repository().fetchData(1, 2);
});

Consumer(
      builder: (context, watch, child) {
      AsyncValue leagueInfo = watch(dataStreamProvider);
      return leagueInfo.when(
          data: (data) {
            print(data);
            return Text("Data");
          },
          loading: () => Loader(""),
          error: (err, stack) => Text('Error: $err'),
        );
    },
)

但是当我尝试将一些参数传递给 StreamProvider 时,我收到了对流的无限调用

// This trigger an infinit call to the stream 'Repository().fetchData'

final dataStreamProvider = StreamProvider.autoDispose.family<DataModel, Map<String, dynamic>>((ref, params) {
      return Repository().fetchData(params['id'], params['id2']);
});

Consumer(
      builder: (context, watch, child) {
      AsyncValue leagueInfo = watch(dataStreamProvider({'id': 1, 'id2': 2}));
      return leagueInfo.when(
          data: (data) {
            print(data);
            return Text("Data");
          },
          loading: () => Loader(""),
          error: (err, stack) => Text('Error: $err'),
        );
    },
)

将您的地图替换为数据-class 和 == 覆盖

class Date {
  final int id1;
  final int id2;
  Date({
    this.id1,
    this.id2,
  });


  @override
  bool operator ==(Object o) {
    if (identical(this, o)) return true;
  
    return o is Date &&
      o.id1 == id1 &&
      o.id2 == id2;
  }

  @override
  int get hashCode => id1.hashCode ^ id2.hashCode;
}


final dataStreamProvider = StreamProvider.autoDispose.family<DataModel, Date>((ref, params) {
      return Repository().fetchData(params.id1, params.id2);
});



Consumer(
      builder: (context, watch, child) {
      AsyncValue leagueInfo = watch(dataStreamProvider(Date(id1: 1,id2: 2)));
      return leagueInfo.when(
          data: (data) {
            print(data);
            return Text("Data");
          },
          loading: () => Loader(""),
          error: (err, stack) => Text('Error: $err'),
        );
    },
)