问题描述
我正在使用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);
},)
],);
}),);
}
}
pubspec.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
的{{1}}方法发出事件。这将导致窗体重置并卸下键盘。自动对焦不起作用,因为有两个TextFormField
wgich发射事件。
解决方法
我也遇到了完全相同的问题。在添加 Unique Key
时,颤动不断构建小部件并且我的键盘每次都没有焦点。我解决的方法是在 TextField 的 onChanged 事件中添加去抖动。
class InputTextWidget extends StatelessWidget {
final Function(String) onChanged;
Timer _debounce;
void _onSearchChanged(String value) {
if (_debounce?.isActive ?? false) _debounce.cancel();
_debounce = Timer(const Duration(milliseconds: 2000),() {
onChanged(value);
});
}
@override
Widget build(BuildContext context) {
return TextFormField(
controller: TextEditingController(text: value)
..selection = TextSelection.fromPosition(
TextPosition(offset: value.length),),onChanged: _onSearchChanged,onEditingComplete: onEditingCompleted,);
}
}
希望这对使用表单、集团和更新表单的人有所帮助。
编辑:虽然添加了去抖动帮助显示了什么。我已将代码更改为更健壮。这是变化。
InputTextWidget
(已更改)
class InputTextWidget extends StatelessWidget {
final Function(String) onChanged;
final TextEditingController controller;
void _onSearchChanged(String value) {
if (_debounce?.isActive ?? false) _debounce.cancel();
_debounce = Timer(const Duration(milliseconds: 2000),() {
onChanged(value);
});
}
@override
Widget build(BuildContext context) {
return TextFormField(
controller: controller,);
}
}
在我的演讲结束时
class _NameField extends StatelessWidget {
const _NameField({
Key key,}) : super(key: key);
@override
Widget build(BuildContext context) {
final TextEditingController _controller = TextEditingController();
return BlocConsumer<SomeBloc,SomeState>(
listenWhen: (previous,current) =>
previous.name != current.name,listener: (context,state) {
final TextSelection previousSelection = _controller.selection;
_controller.text = state.name;
_controller.selection = previousSelection;
},buildWhen: (previous,builder: (context,state) => FormFieldDecoration(
title: "Name",child: InputTextWidget(
hintText: "AWS Certification",textInputType: TextInputType.name,controller: _controller,onChanged: (value) => context
.read< SomeBloc >()
.add(SomeEvent(
value)),);
}
}
此编辑工作正常。
最终编辑:
我在我的区块状态中添加了一个 key? key
并将这个键传递给小部件。如果我需要再次重绘表单,我将事件中的键更改为 UniqueKey
。这是迄今为止我将 bloc 和 form 一起实现的最简单的方法。如果需要解释,请在此评论,我稍后补充。
您可以复制粘贴以下运行完整代码1和2的代码
您可以向UniqueKey()
或Scaffold
提供TextFormField
来强制重新创建
您可以参考https://medium.com/flutter/keys-what-are-they-good-for-13cb51742e7d了解详情
如果Element的键与相应的Widget的键不匹配。这会导致Flutter停用这些元素,并删除元素树中对元素的引用
解决方案1:
return Scaffold(
key: UniqueKey(),body: Form(
解决方案2:
TextFormField(
key: UniqueKey(),
工作演示
完整代码1 Scaffold
与UniqueKey
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) {
print("build");
return MaterialApp(
home: BlocProvider(
create: (_) => ExampleBloc(),child: Builder(
builder: (contex) => SafeArea(
child: BlocConsumer<ExampleBloc,int>(
listener: (context,state) {},int state) {
print("state ${state.toString()}");
developer.log(state.toString());
return Scaffold(
key: UniqueKey(),body: Form(
child: Column(
children: [
TextFormField(
autocorrect: false,initialValue: state.toString(),RaisedButton(
child: Text('Press'),onPressed: () {
context.bloc<ExampleBloc>().add(Event.first);
},)
],);
}),);
}
}
完整代码2 TextFormField
与UniqueKey
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 state) {
print("state ${state.toString()}");
developer.log(state.toString());
return Scaffold(
body: Form(
child: Column(
children: [
TextFormField(
key: UniqueKey(),autocorrect: false,);
}
}
,
您不应仅仅因为要更新Form
的值,尝试使用TextFormField
并更新侦听器上的值而重建整个TextEditingController
。
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,initialValue: context.bloc<ExampleBloc>().state.toString()
),RaisedButton(
child: Text('Press'),onPressed: () {
context.bloc<ExampleBloc>().add(Event.first);
},)
],);
}),