flutter 我如何调用构建中的futureprovider(riverpod

unguejic  于 2023-01-27  发布在  Flutter
关注(0)|答案(4)|浏览(222)

我有一个简单的页面,它显示了一个产品,我正在尝试使用riverpod,和futureprovider,但未来只是调用我第一次去的页面?

final productInfo = FutureProvider<Map<String, dynamic>>((ref) async {
  final response =
      await http.get('https://www.api.com/$clickedID');
  final content = json.decode(response.body) as Map<String, dynamic>;
  return content;
});
u59ebvdq

u59ebvdq1#

使用最新的Riverpod,您可以执行ref.refresh(userProvider)来刷新提供程序。

v440hwme

v440hwme2#

请使用

final userProvider = StreamProvider<User>(
 final response =
      await http.get('https://www.api.com/$clickedID');
  final content = json.decode(response.body) as Map<String, dynamic>;
  return content;
);

现在您可以使用watch侦听提供程序,

AsyncValue<User> user = watch(userProvider);
nkkqxpd9

nkkqxpd93#

没有内置功能,但您可以在以后用相同的将来值覆盖该值。

recallProductInfoFutureProvider() {
final response = http.get('https://www.api.com/$clickedID');
  final content = json.decode(response.body) as Map<String, dynamic>;
productInfo.overrideWithValue(content)
}

请考虑与StreamProvider一起使用并在Consumer内部进行监视,以更新overrideWithValue上的UI。

iqjalb3h

iqjalb3h4#

有两个选择。
1.引用刷新(提供程序)
1.引用无效(提供程序)
请注意,如果使用的是AsyncValue,则在刷新FutureProvider时将返回旧结果,并且AsyncValue.isRefreshing将设置为true:

final notificationRepositoryProvider = FutureProvider<bool?>((ref) async {
  Future<bool> approveDocument() => Future.delayed(Duration(seconds: 1), () => Future.value(Random().nextBool()));

  return approveDocument();
});

class HomeView extends ConsumerStatefulWidget {
  const HomeView({Key? key}) : super(key: key);

  @override
  HomeViewState createState() => HomeViewState();
}

class HomeViewState extends ConsumerState<HomeView> {
  @override
  Widget build(BuildContext context) {
    AsyncValue<bool?> rejectResponse = ref.watch(notificationRepositoryProvider);
    return ElevatedButton(
        onPressed: () {
          // ref.refresh(notificationRepositoryProvider);
          ref.watch(notificationRepositoryProvider).;
        },
        child: rejectResponse.when(
          loading: () => const CircularProgressIndicator(
            color: Colors.white,
          ),
          skipLoadingOnRefresh: false,
          error: (err, stack) => Text('Error'),
          data: (data) => Text('Yes: $data'),
        ));
  }
}

相关问题