如何在 flutter 中覆盖 Widget 函数
How to override Widget function in flutter
我有这个Widget功能:
static Widget mainButton(String title){
return MaterialButton(
textColor: Colors.white,
splashColor: Colors.white54,
elevation: 8.0,
child: Container(
width: 244,
height: 66,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/home_button_bg.png'),
fit: BoxFit.cover),
),
child: Center(
child: Text(
title,
style: TextStyle(
fontSize: 20.0,
),
),
),
),
onPressed: (){
print('pressed');
},
);
}
并且我想在每次调用 mainButton()
函数时以不同的方式编写 onPressed()
函数。
怎么写呢?
Widget mainButton(String title, VoidCallback onPressed){
return MaterialButton(
textColor: Colors.white,
splashColor: Colors.white54,
elevation: 8.0,
child: Container(
width: 244,
height: 66,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/home_button_bg.png'),
fit: BoxFit.cover),
),
child: Center(
child: Text(
title,
style: TextStyle(
fontSize: 20.0,
),
),
),
),
onPressed: onPressed,
);
}
示例:
mainButton("Test", () {
print('Test');
});
您可以像下面的代码一样使用 Function 来输入此方法:
static Widget mainButton(String title, Function function) {
return MaterialButton(
textColor: Colors.white,
splashColor: Colors.white54,
elevation: 8.0,
child: Container(
width: 244,
height: 66,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/home_button_bg.png'),
fit: BoxFit.cover),
),
child: Center(
child: Text(
title,
style: TextStyle(
fontSize: 20.0,
),
),
),
),
onPressed: function);
}
我有这个Widget功能:
static Widget mainButton(String title){
return MaterialButton(
textColor: Colors.white,
splashColor: Colors.white54,
elevation: 8.0,
child: Container(
width: 244,
height: 66,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/home_button_bg.png'),
fit: BoxFit.cover),
),
child: Center(
child: Text(
title,
style: TextStyle(
fontSize: 20.0,
),
),
),
),
onPressed: (){
print('pressed');
},
);
}
并且我想在每次调用 mainButton()
函数时以不同的方式编写 onPressed()
函数。
怎么写呢?
Widget mainButton(String title, VoidCallback onPressed){
return MaterialButton(
textColor: Colors.white,
splashColor: Colors.white54,
elevation: 8.0,
child: Container(
width: 244,
height: 66,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/home_button_bg.png'),
fit: BoxFit.cover),
),
child: Center(
child: Text(
title,
style: TextStyle(
fontSize: 20.0,
),
),
),
),
onPressed: onPressed,
);
}
示例:
mainButton("Test", () {
print('Test');
});
您可以像下面的代码一样使用 Function 来输入此方法:
static Widget mainButton(String title, Function function) {
return MaterialButton(
textColor: Colors.white,
splashColor: Colors.white54,
elevation: 8.0,
child: Container(
width: 244,
height: 66,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/home_button_bg.png'),
fit: BoxFit.cover),
),
child: Center(
child: Text(
title,
style: TextStyle(
fontSize: 20.0,
),
),
),
),
onPressed: function);
}