App主体,因为只是做示例,没有做页面变化的效果,所以使用了StatelessWidget这个类
class myApp extends StatelessWidget {
String actionName;
//declare & create object
Lee classLee = new Lee();
//create string only array
List<String> actions = ['First Button Click','Second Button Click','Third Button Click'];
void onPressFirstBtn(){
classLee.action_name = actions[0];
classLee.action();
}
void onPressSecondBtn(){
classLee.action_name = actions[1];
classLee.action();
}
void onPressThirdBtn(){
classLee.action_name = actions[2];
classLee.action();
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
appBar: AppBar(
title: Text('Bar Title'),
),
body: Center(
child: Column(
children: <Widget>[
new MyButton(
onPress: onPressFirstBtn,
title: Text('First_Btn'),
icon: Icon(Icons.favorite),
),
new MyButton(
onPress: onPressSecondBtn,
title: Text('Second_Btn'),
icon: Icon(Icons.favorite),
),
new MyButton(
onPress: onPressThirdBtn,
title: Text('third_Btn'),
icon: Icon(Icons.favorite),
)
],
),
),
);
}
}
按钮,其中声明了回调函数onPress,并将其与其它属性放入该类的构造方法中
class MyButton extends StatelessWidget {
//callback
@required VoidCallback onPress;
Text title;
Icon icon;
//constructor
MyButton({this.onPress,this.title,this.icon});
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Container(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new FlatButton(
onPressed: onPress,//这里为回调函数的使用,即每次按钮触发点击事件则调用回调函数
color: Colors.pink[100],
child: new Column(
children: <Widget>[
this.title,
this.icon
],
),
),
],
),
);
}
}
最后这个类为测试使用,不同的按钮点击会log出不同的actionName
class Lee{
String action_name;
Lee({this.action_name});
void action() {
print('$action_name');
}
}
网友评论