8.父Widget管理子Widget的状态
class ParentWidget extends StatefulWidget {
@override
_ParentWidgetState createState() => new _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
//state的数据
bool _active = false;
void _handleTapboxChanged(bool newValue) {
setState(() {
_active = newValue;
});
}
@override
Widget build(BuildContext context) {
return new Container(
//创建TapboxB传入变量active和函数_handleTapboxChanged作为参数
child: new TapboxB(
active: _active,
onChanged: _handleTapboxChanged,
),
);
}
}
class TapboxB extends StatelessWidget {
//state类接收statefulWidget类传入的参数
TapboxB({Key key,@required this.active, @required this.onChanged})
: super(key: key);
final bool active;
final ValueChanged<bool> onChanged;
//触发statefulWidget类的setState函数,改变state的数据,重新build
void _handleTap() {
onChanged(!active);
}
Widget build(BuildContext context) {
//GestureDetector监听所有tap事件
return new GestureDetector(
//点击时触发函数
onTap: _handleTap,
child: new Container(
child: new Center(
child: new Text(
active ? 'Active' : 'Inactive',
style: new TextStyle(fontSize: 32.0, color: Colors.white),
),
),
width: 200.0,
height: 200.0,
//改变背景颜色
decoration: new BoxDecoration(
color: active ? Colors.lightGreen[700] : Colors.grey[600],
),
),
);
}
}
结果:
9.Text文本的属性
Text("Hello world",
//文本左对齐
textAlign: TextAlign.left,
),
//文本重复4次
Text("Hello world! I'm Jack. "*4,
//文本显示最大行数
maxLines: 1,
//文本截断,多余的用...代替
overflow: TextOverflow.ellipsis,
),
Text("Hello world",
//字体缩放
textScaleFactor: 1.5,
),
//设置样式
Text("I am Jack",
style: TextStyle(
//设置颜色
color: Colors.grey
//设置字体
fontFamily: 'Raleway',
),
),
10.漂浮按钮
RaisedButton(
child: Text("normal"),
onPressed: () {},
);
11.扁平按钮
FlatButton(
child: Text("normal"),
onPressed: () {},
)
12.带边框按钮
OutlineButton(
child: Text("normal"),
onPressed: () {},
)
13.图标按钮
IconButton(
icon: Icon(Icons.thumb_up),
onPressed: () {},
)
14.加载图片
(1)修改pubspec.yaml
flutter:
assets:
- images/asd.png
(2)加载图片
body: Image(
image: AssetImage("images/asd.png"),
width: 100.0
),
效果:
15.加载图标
Icon(Icons.accessible,color: Colors.green,),
效果:
16.单选框和复选框
class SwitchAndCheckBoxTestRoute extends StatefulWidget {
@override
_SwitchAndCheckBoxTestRouteState createState() => new _SwitchAndCheckBoxTestRouteState();
}
class _SwitchAndCheckBoxTestRouteState extends State<SwitchAndCheckBoxTestRoute> {
bool _switchSelected=true; //维护单选开关状态
bool _checkboxSelected=true;//维护复选框状态
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Switch(
value: _switchSelected,//当前状态
onChanged:(value){
//重新构建页面
setState(() {
_switchSelected=value;
});
},
),
Checkbox(
value: _checkboxSelected,
activeColor: Colors.red, //选中时的颜色
onChanged:(value){
setState(() {
_checkboxSelected=value;
});
} ,
)
],
);
}
}
效果: