假设我有一个TextField
这样的人
TextEditingController textController = TextEditingController()
...
TextField(
controller: textController
)
并假设我有一个使用TextField
控制器并在其中打印一些文本的库。
是否可以通过TextField
来更改controller
或任何其他小部件的属性?
例如:禁用TextField
如果No
怎么在我的库中而不是在Stateful
小部件中
答案 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});
}