如何正确提取/合成自定义小部件并处理其子字段

时间:2019-11-22 18:18:17

标签: flutter

在我的小部件树中,我有几个TextField小部件。所有的装饰都相同,但onChanged动作却不同:

Widget _buildTextField() {
  return TextField (
    decoration: InputDecoraction(
      border: OutlineInputBorder()
    ),
    onChanged: (text) {
      doSth();
    }
  );
}

现在,我想减少代码重复,并尝试将具有重复的TextField字段的decoration提取到CustomTextField中。我读到Flutter的合成超过了继承,因此我尝试通过这种方式进行合成:

class CustomTextField extends StatefulWidget {
  @override
  _CustomTextFieldState createState() => _CustomTextFieldState();
}

class _CustomTextFieldState extends State<CustomTextField> {    
  @override
  Widget build(BuildContext context) {
    return Container(
      child: TextField(
        decoration: InputDecoration(     //   <-- the decoration field
          border: OutlineInputBorder(),
        ),
      ),
    );
  }
}

我在另一边做了

Widget _buildTextField() {
  return CustomTextField (               //   <-- new CustomTextField without decoration
    onChanged: (text) {                  //   <-- Problem: "Parameter is not defined"
      doSth();
    }
  );
}

但是现在不接受onChanged呼叫。那么,提取自己的小部件并处理子字段的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您需要注册一个回调函数

class CustomTextField extends StatefulWidget {
  final Function onChange;

  const CustomTextField({Key key, this.onChange}) : super(key: key);

  @override
  _CustomTextFieldState createState() => _CustomTextFieldState();
}

class _CustomTextFieldState extends State<CustomTextField> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: TextField(
        decoration: InputDecoration(
          //   <-- the decoration field
          border: OutlineInputBorder(),
        ),
        onChanged: widget.onChange,
      ),
    );
  }
}

然后

  child: CustomTextField(
    onChange: (item) {
      print(item);
    },
  ),