在以下代码中使用Riverpod。我不希望通过重新构建来更新textField值,我只想在第一次从状态中获取值,并且需要不断地监听状态以更新其他内容。
如果用户更新了字段,那么小部件就重新构建了,我需要保持用户的值而不刷新。
class Example extends ConsumerWidget {
const Example({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(myStateProvider);
return TextFormField(
controller: TextEditingController(text: state.firstName.value),
textInputAction: TextInputAction.next,
decoration: InputDecoration(
labelText: 'First Name', errorText: state.firstName.errorMessage),
);
}
}
不使用onChange
的
发布于 2022-02-21 12:51:49
您可以使用ConsumerStatefulWidget
class Example extends ConsumerStatefulWidget {
const Example({
Key? key,
}) : super(key: key);
@override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends ConsumerState<Example> {
final _textEditingController = TextEditingController();
@override
void initState() {
super.initState()
_textEditingController.text = ref.read(myStateProvider).firstName.value;
}
@override
void dispose() {
_textEditingController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(myStateProvider);
return TextFormField(
controller: _textEditingController,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
labelText: 'First Name', errorText: state.firstName.errorMessage),
);
}
}
https://stackoverflow.com/questions/71206519
复制相似问题