在两个类中为控制器创建一个属性,在主类中创建控制器,然后将其传递给表单类。
class MainWidget extends StatelessWidget {
// create controller
final txtFieldController = TextEditingController();
// pass the controller to the other class \/
final formWidget = FormWidget(txtFieldController: txtFieldController);
// ...
}
class FormWidget extends StatelessWidget {
// create controller
final TextEditingController txtFieldController;
// ...
}
完整示例代码:
表单小部件
class FormWidget extends StatelessWidget {
// create a property for the controller \/
final TextEditingController txtFieldController;
const FormWidget({Key key, this.txtFieldController}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: TextFormField(
controller: txtFieldController,
),
);
}
}
主小部件
class MainWidget extends StatefulWidget {
@override
_MainWidgetState createState() => _MainWidgetState();
}
class _MainWidgetState extends State<MainWidget> {
final txtFieldController = TextEditingController();
@override
void initState() {
// updates the widget on changes
// note, the docs say: 'Avoid calling setState() high up in the tree if the change is contained to a small part of the tree.'
// but it's not a big deal in this case
txtFieldController.addListener(() {
setState(() {});
});
super.initState();
}
@override
void dispose() {
txtFieldController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'This is a Text',
style: TextStyle(
color: txtFieldController.value.text.isEmpty ? Colors.red : Colors.green,
),
),
// pass the controller to the other class \/
FormWidget(txtFieldController: txtFieldController)
],
),
),
);
}
}