将 TextEditingController 定义/实例化为 GetxController 中的一个字段,用于控制表单/实现业务逻辑。
class DestinoFormControllerX extends GetxController {
static DestinoFormControllerX get i => Get.find();
final GlobalKey<FormBuilderState> key = GlobalKey<FormBuilderState>();
// ↓ place the text editing controller inside your... controller :)
var controllerDestino = TextEditingController();
并在 GetxController 中任何需要的地方使用 TextEditingController 值
void resetForm() {
key.currentState.reset();
controllerDestino.text = '';
focusNode.requestFocus();
}
在您的视图层中,注入您的 GetxController,并获取文本编辑控制器并访问您需要的任何其他方法/字段。
class DestinoForm extends StatelessWidget {
final void Function() submitHandler;
DestinoForm({this.submitHandler});
@override
Widget build(BuildContext context) {
final dcx = Get.put(DestinoFormControllerX());
// ↑ inject GetxController, be careful to put *inside* build method
return FormBuilder(
key: dcx.key,
child: Column(
children: [
FormBuilderTextField(
name: 'destino',
controller: dcx.controllerDestino,
decoration: InputDecoration(
labelText: 'Destino',
),
大多数表单都有重置和提交按钮。在那里你可以调用 GetxController 上的方法......
actions: [
FlatButton(
child: Text('Reset'),
onPressed: () => DestinoFormControllerX.i.resetForm(),
),
边注
如果您在 Form Widget 中实例化/注入 GetxController,请在 Form Widget的方法Get.put()
中执行此操作。build
否则,您可能会TextEditingController
调用setState
不再安装在小部件树中的 StatefulWidget(文本字段):
════════ Exception caught by foundation library ════════════════════════════════════════════════════
The following assertion was thrown while dispatching notifications for TextEditingController:
setState() called after dispose(): _FormBuilderTextFieldState#96390(lifecycle state: defunct, not mounted)
好的
class DestinoForm extends StatelessWidget {
final void Function() submitHandler;
DestinoForm({this.submitHandler});
@override
Widget build(BuildContext context) {
final dcx = Get.put(DestinoFormControllerX());
// ↑ inject GetxController, be careful to put *inside* build method
坏的
class DestinoForm extends StatelessWidget {
final void Function() submitHandler;
final dcx = Get.put(DestinoFormControllerX());
// ↑ wrong place, DestinoFormControllerX gets linked to previous route
DestinoForm({this.submitHandler});
@override
Widget build(BuildContext context) {
有关 Github 的更多详细信息,提到了 GetX 的正确注入/使用。