在颤动中通过其控制器更改窗口小部件属性

时间:2019-01-17 20:11:56

标签: flutter

假设我有一个TextField这样的人


TextEditingController textController = TextEditingController()

...

TextField(
    controller: textController
)

并假设我有一个使用TextField控制器并在其中打印一些文本的库。

是否可以通过TextField来更改controller或任何其他小部件的属性?
例如:禁用TextField

如果No怎么在我的库中而不是在Stateful小部件中

1 个答案:

答案 0 :(得分:0)

我创建了此样本,您可以看一下:

SampleTextField类扩展了StatefulWidget {           @override           SampleTextFieldState createState(){             返回新的SampleTextFieldState();           }         }

    class SampleTextFieldState extends State<SampleTextField> {
      MyCustomController customController =
          MyCustomController(controller: TextEditingController());

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Column(
              children: [
                MyCustomTextField(
                  customController: customController,
                ),
                OutlineButton(
                  onPressed: () {
                    setState(() {
                      customController.controller.text = "new value";
                    });
                  },
                  child: Text("set text"),
                ),
                OutlineButton(
                  onPressed: () {
                    setState(() {
                      customController.enable = false;
                    });
                  },
                  child: Text("disable textfield"),
                ),
                OutlineButton(
                  onPressed: () {
                    setState(() {
                      customController.enable = true;
                    });
                  },
                  child: Text("enable textfield"),
                )
              ],
            ),
          ),
        );
      }
    }

    class MyCustomTextField extends StatelessWidget {
      final MyCustomController customController;

      const MyCustomTextField({Key key, this.customController}) : super(key: key);

      @override
      Widget build(BuildContext context) {
        return TextFormField(
          controller: customController.controller,
          enabled: customController.enable,
        );
      }
    }

    class MyCustomController {
      final TextEditingController controller;
      bool enable;

      MyCustomController({@required this.controller, this.enable = true});
    }