WidgetStateless
函数 Widget
写过 React 的人都知道纯函数组件,flutter 类比过来可以是这样:
Widget helloRect() {
return Container(
color: Colors.purple,
width: 200,
height: 200,
margin: EdgeInsets.all(16),
child: Center(child: Text('Hi')),
);
}
StatelessWidget
但是 Flutter 中最常用的是 StatelessWidget:
class HelloRect extends StatelessWidget {
final String text;
HelloRect({this.text});
Widget build(BuildContext context) {
return Container(
color: Colors.purple,
width: 200,
height: 200,
margin: EdgeInsets.all(16),
child: Center(child: Text(text)),
);
}
}
从 dart 语法来看 Widget 参数
上面的语法对于 dart 不熟悉的人可能会看不懂,这其实是 dart 的语法糖,不用的话就是这样:
// 不使用语法糖
class HelloRect extends StatelessWidget {
final String text;
// HelloRect({this.text}); // 在构造函数中可以直接将 this 替换
HelloRect({String text}) { // text 是 String 类型的可选参数
this.text = text;
}
Widget build(BuildContext context) {
return Container(
color: Colors.purple,
width: 200,
height: 200,
margin: EdgeInsets.all(16),
// child: Center(child: Text(text)), // dart 中 this 是可省略的
child: Center(child: Text(this.text)),
);
}
}
这一段看懂之后就运行下面的代码,再看效果 :