flutter - Flutter Bloc 不会改变 TextFormField 的初始值
问题描述
我正在使用 Bloc 库并注意到在产生新状态后我的TextFormField
initialValue 没有改变。
我的应用程序比这更复杂,但我做了一个最小的例子。还跟踪推送事件后它正在更改的状态。
Bloc 应该正确地重建整个小部件。我错过了什么吗?
import 'package:flutter/material.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'dart:developer' as developer;
void main() {
runApp(MyApp());
}
enum Event { first }
class ExampleBloc extends Bloc<Event, int> {
ExampleBloc() : super(0);
@override
Stream<int> mapEventToState(Event event) async* {
yield state + 1;
}
}
class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: BlocProvider(
create: (_) => ExampleBloc(),
child: Builder(
builder: (contex) => SafeArea(
child: BlocConsumer<ExampleBloc, int>(
listener: (context, state) {},
builder: (context, int state) {
developer.log(state.toString());
return Scaffold(
body: Form(
child: Column(
children: [
TextFormField(
autocorrect: false,
initialValue: state.toString(),
),
RaisedButton(
child: Text('Press'),
onPressed: () {
context.bloc<ExampleBloc>().add(Event.first);
},
)
],
),
),
);
}),
),
),
),
);
}
}
发布规范.yaml
name: form
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
bloc: ^6.0.0
flutter_bloc: ^6.0.0
编辑
@chunhunghan 指出添加 UniqueKey 解决了这个问题。我也应该提到我的情况。onChanged
该应用程序从两个的方法发出事件TextFormField
。这会导致窗体重置并删除键盘。自动对焦不起作用,因为有两个TextFormField
wgich 发射事件。
解决方案
您不应该Form
仅仅因为要更新 的值而重建整个TextFormField
,请尝试使用 aTextEditingController
并更新侦听器上的值。
TextEditingController _controller = TextEditingController();
BlocProvider(
create: (_) => ExampleBloc(),
child: Builder(
builder: (contex) => SafeArea(
child: BlocListener<ExampleBloc, int>(
listener: (context, state) {
_controller.text = state.toString();
},
child: Scaffold(
body: Form(
child: Column(
children: [
TextFormField(
controller: _controller,
autocorrect: false,
),
RaisedButton(
child: Text('Press'),
onPressed: () {
context.bloc<ExampleBloc>().add(Event.first);
},
)
],
),
),
);
}),
推荐阅读
- c - 为什么我的代码中出现分段错误?无法调试,请解释错误
- python - 将指标/结果组合成一个数据框 python
- java - 请求标头编码更改为空正文
- nativescript - 如何仅更新项目中的“nativescript-vue”包?
- reactjs - React UI - 从文件浏览器获取文件的绝对路径
- google-cloud-firestore - 检查用户名是否存在于firestore中并返回true swiftUI
- python - 必须运行 glob.glob 两次才能工作(Python3)
- sql - oracle CASE WHEN 语句中如何查找重复记录
- r - for 循环中的嵌套 if 语句,“条件长度 > 1 且仅使用第一个元素”
- angular - 如何将存储(用户会话)数据传递到侧菜单离子 5?