在useEffect中读取riverpod流值

Read riverpod stream value in useEffect

我想从 useEffect 中的列表流中读取第一个值到 select 返回列表中的第一个值。我该怎么做?

重新启动时显示错误。

我正在使用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);