如何使用 Getx 检索控制器层内的 TextEditingController?

How to retrieve a TextEditingController inside a Controller layer with Getx?

我的视图层中有这个语句

TextEditingController controllerDestino = TextEditingController();

而且我想恢复这个 controllerDestino,以便在我的 Controller 层中的方法中使用。

 statusUberNaoChamado() {
showBoxAdress = true;

changeMainButton("Chamar", Color(0xFF1ebbd8), () {
  callUber("I need pass the controller here");
});

update();}

提前感谢您的关注:)

Define/instantiate 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,并获取文本编辑控制器并访问您需要的任何其他 methods/fields。

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(),
        ),

旁注

如果您使用 Get.put() 在表单小部件中实例化/注入 GetxController,请在表单小部件的 build 方法 中执行此操作。

否则,您可能会 TextEditingController 在不再安装在小部件树中的 StatefulWidget(文本字段)上调用 setState

════════ 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) {

More detail on Github,提及正确注入/使用 GetX。