0

我使用一个函数在颤振中创建了两个文本字段,但我想为每个字段使用两个不同的 TextEditingController。如何将 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'),
        ],
      );
    }
4

3 回答 3

1

像过去一样

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),
            ),
          ),
        );

}

于 2020-09-15T15:09:58.800 回答
1

您可以将其作为参数传递给您的函数:

         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),
        ],
      );
    }
于 2020-09-15T15:10:07.130 回答
0

如果您的 fieldMaker 方法是 FieldMaker 扩展 StatefulWidget 的类,则该类可以创建 TextController 并根据标题对其进行配置。那么你也能:

children: <Widget>[
  FieldMaker('Title'),
  FieldMaker('Amount'),
]
于 2020-09-15T15:51:00.647 回答