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

时间:2021-01-27 02:58:15

标签: flutter dart getx

我的视图层中有这个语句

TextEditingController controllerDestino = TextEditingController();

我想恢复这个 controllerDestino,以便在我的控制器层中的方法中使用。

 statusUberNaoChamado() {
showBoxAdress = true;

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

update();}

预先感谢您的关注:)

1 个答案:

答案 0 :(得分:1)

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

附注

如果您使用 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 的正确注入/使用。