将 TextEditingController 作为参数传递给函数?

Passing TextEditingController as a paramater to a function?

我使用一个函数在 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'),
        ],
      );
    }

点赞

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

}

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

         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 方法是 class FieldMaker extends StatefulWidget,class 可以创建 TextController 并根据标题对其进行配置。然后你可以:

children: <Widget>[
  FieldMaker('Title'),
  FieldMaker('Amount'),
]