gpt4 book ai didi

flutter - 如何使用 flutter riverpod statenotifier、ref watch 和 asyncvalue 获取加载状态/微调器?

转载 作者:行者123 更新时间:2023-12-05 09:26:41 33 4
gpt4 key购买 nike

我有下面的示例,它确实刷新了数据,但没有按预期提供微调器。我尝试使用 ref.listen 切换到异步加载,我尝试在调用前等待,即使它没有意义。

我尝试了 ref.refresh、ref.invalidate...预期行为:打开应用,查看微调器,点击按钮,在文本更改之前再次查看微调器。实际行为:打开应用,看到微调器,点击按钮,文本发生变化,但没有微调器显示。另见 https://github.com/neiljaywarner/riverpod_watching_dep_no_spinner_sample我正在使用 flutter 3.0.5 和 hooks_riverpod: ^2.0.0-dev.9。

import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

void main() => runApp(ProviderScope(child: MyApp()));

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) => MaterialApp(title: 'Riverpod Spinner Demo',
theme: ThemeData(primarySwatch: Colors.blue), home: MyHomePage());
}

class MyHomePage extends ConsumerWidget {

@override
Widget build(BuildContext context, WidgetRef ref) => Scaffold(
appBar: AppBar(title: const Text('Riverpod Spinner Question'),),
body: ref.watch(futureProvider).when(data: (data) => Column(
children: [
ElevatedButton(onPressed: () => ref.read(paramProvider.notifier).state = 'new value',
child: const Text('pretend update')),
Text(data)],
),
error: (_,__) => const Text('something went wrong'),
loading: () => const CircularProgressIndicator())
);
}

final paramProvider = StateProvider((ref) => 'Initial value');

final futureProvider = FutureProvider.autoDispose<String>((ref) async {
String parameter = ref.watch(paramProvider);
return pretendApiCall(parameter);
});
Future<String> pretendApiCall(String parameter) async {
await Future.delayed(const Duration(seconds: 3));
return parameter;
}

最佳答案

啊。

var asyncValue = ref.watch(futureProvider);
return Scaffold(
appBar: AppBar(title: const Text('Riverpod Spinner Question'),),
body: asyncValue.when(data: (data) {
if (asyncValue.isRefreshing) return const CircularProgressIndicator();
return Column(
children: [
ElevatedButton(onPressed: () => ref.read(paramProvider.notifier).state = 'new value',
child: const Text('pretend update')),
Text(data)],
);
},

关于flutter - 如何使用 flutter riverpod statenotifier、ref watch 和 asyncvalue 获取加载状态/微调器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73588646/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com