在 useEffect 中读取 riverpod 流值

问题描述

我想从 useEffect 中的列表流中读取第一个值以选择返回列表中的第一个值。我如何以不同的方式执行此操作。

重启时显示错误。

我正在使用 hooks_riverpod

    
    final _locations = useProvider(locationsProvider); // provides AsyncValue<List<FacilityLocation>> 
    final _selectedLocationID = useState('');

    useEffect(() {
      _locations.when(
        data: (locations) {
          final _location = locations[0];
          return _selectedLocationID.value = _location.locationID;
        },loading: null,error: (err,stack) => null,);
      return;
    },[]);

解决方法

为什么不为列表中的第一个值创建另一个提供程序呢?您还可以为列表中第一个值的 id 创建一个额外的提供者。而不是在构建函数中处理所有这些逻辑。

class Facility {
  const Facility(this.id);

  final String id;
}

final locationsProvider =
    StreamProvider<List<Facility>>((_) => Stream.value([Facility('A'),Facility('B')]));

final firstLocation = FutureProvider<Facility>((ref) async {
  final locations = await ref.watch(locationsProvider.last);
  return locations.first;
});

// Can also do this as a FutureProvider,just wanted to add flavor.
final firstLocationId = Provider<String?>((ref) => ref.watch(firstLocation).data?.value.id);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...