有人可以举一个最好使用riverpod_hooks在Riverpods中进行额外状态修改的例子 - 我希望能够在不制作额外小部件的情况下使用它,例如:
onPress: () {
useProvider(genderProvider).state = Gender.female;
},
一旦实施,我在理解有关使用提供程序的 Riverpods 文档时遇到了一些困难。我理解增量部分.state++,但我找不到初始化后更改状态值的明确示例。因为 x 被初始化为零,但您只想将其设为 42 或输入值。
例如,我有一个 Gender {male, women, non-binary} 枚举,我创建了一个 GenderProvider,但是我无法找出使用按钮更改应用程序中性别的最佳方法。我也不完全确定 Provider 和 RiverPods 有多少相似,似乎有很多语义差异?
这是当前在我的代码中声明提供程序的方式:
enum Gender {
male,
female,
nonBinary
}
final genderProvider = StateProvider((_) => Gender.female);
提前致谢,感谢您的建议。
答案 0 :(得分:0)
onPress: () => context.read(genderProvider).state = Gender.female,
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
void main() {
runApp(
ProviderScope(
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomePage(),
),
),
);
}
class HomePage extends HookWidget {
@override
Widget build(BuildContext context) {
final gender = useProvider(genderProvider).state;
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Gender: ${describeEnum(gender)}'),
const SizedBox(height: 16.0),
ElevatedButton(
child: Text('MALE'),
onPressed: () => context.read(genderProvider).state = Gender.male,
),
const SizedBox(height: 8.0),
ElevatedButton(
child: Text('FEMALE'),
onPressed: () =>
context.read(genderProvider).state = Gender.female,
),
],
),
),
);
}
}
enum Gender { male, female, nonBinary }
final genderProvider = StateProvider((_) => Gender.female);