在我的小部件树中,我有几个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
呼叫。那么,提取自己的小部件并处理子字段的正确方法是什么?
答案 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);
},
),