gpt4 book ai didi

Flutter Bloc 不会改变 TextFormField initialValue

转载 作者:行者123 更新时间:2023-12-04 01:15:58 24 4
gpt4 key购买 nike

我正在使用 Bloc 库并在产生新状态后注意到我的 TextFormField初始值不会改变。
我的应用程序比这更复杂,但我做了一个最小的例子。还跟踪它在推送事件后正在改变的状态。
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 发出事件方法二 TextFormField .这会导致窗体重置并移除键盘。自动对焦不起作用,因为有两个 TextFormField wgich 发出事件。

最佳答案

您不应该重建整个 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,
autocorrect: false,
),
RaisedButton(
child: Text('Press'),
onPressed: () {
context.bloc<ExampleBloc>().add(Event.first);
},
)
],
),
),
);
}),

关于Flutter Bloc 不会改变 TextFormField initialValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63367800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com