我使用一个函数在flutter中创建了两个文本字段,但我想为每个字段使用两个不同的TextEditingControllers。如何将TextEditingController作为参数传递给函数?
Widget fieldmaker(String title) {
return Container(
width: double.infinity,
height: 50,
padding: EdgeInsets.symmetric(
horizontal: 10,
),
child: TextField(
controller: ,
decoration: InputDecoration(
hintText: title,
hintStyle: TextStyle(
fontSize: 20,
),
contentPadding: EdgeInsets.all(2),
),
),
);
}
final amountcontroller=TextEditingController();
final titlecontroller=TextEditingController();
Widget build(BuildContext context) {
return Column(
children: [
fieldmaker('Title'),
fieldmaker('Amount'),
],
);
}
您可以将其作为参数传递给函数:
Widget fieldmaker(String title,TextEditingController controller) {
return Container(
width: double.infinity,
height: 50,
padding: EdgeInsets.symmetric(
horizontal: 10,
),
child: TextField(
controller: controller,
decoration: InputDecoration(
hintText: title,
hintStyle: TextStyle(
fontSize: 20,
),
contentPadding: EdgeInsets.all(2),
),
),
);
}
final amountcontroller=TextEditingController();
final titlecontroller=TextEditingController();
Widget build(BuildContext context) {
return Column(
children: [
//pass them to the function from here
fieldmaker('Title',titlecontroller),
fieldmaker('Amount',amountcontroller),
],
);
}
像一样传递
fieldmaker('Title', amountcontroller);
并修改您的功能
fieldmaker(String title, TextEditingController yourTextEditingController){
//use yourTextEditingController here
return Container(
width: double.infinity,
height: 50,
padding: EdgeInsets.symmetric(
horizontal: 10,
),
child: TextField(
controller: yourTextEditingController,
decoration: InputDecoration(
hintText: title,
hintStyle: TextStyle(
fontSize: 20,
),
contentPadding: EdgeInsets.all(2),
),
),
);
}
如果您的fieldMaker方法是一个类fieldMaker扩展StatefulWidget,则该类可以创建TextController并基于标题对其进行配置。然后你可以:
children: <Widget>[
FieldMaker('Title'),
FieldMaker('Amount'),
]