首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >防止更新TextField (Riverpod)

防止更新TextField (Riverpod)
EN

Stack Overflow用户
提问于 2022-02-21 12:42:38
回答 1查看 456关注 0票数 1

在以下代码中使用Riverpod。我不希望通过重新构建来更新textField值,我只想在第一次从状态中获取值,并且需要不断地监听状态以更新其他内容。

如果用户更新了字段,那么小部件就重新构建了,我需要保持用户的值而不刷新。

代码语言:javascript
运行
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-21 12:51:49

您可以使用ConsumerStatefulWidget

代码语言:javascript
运行
复制
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),
    );
  }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71206519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档