Widget 管理自身状态
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
///TapboxA 类
class TapboxA extends StatefulWidget {
TapboxA({Key key}) : super(key: key);
@override
_TapboxAState createState() => new _TapboxAState();
}
class _TapboxAState extends State<TapboxA> {
bool _active = false;
void _handleTap() {
setState(() {
_active = !_active;
});
}
@override
Widget build(BuildContext context) {
return new GestureDetector(
onTap: _handleTap,
child: new Container(
child: new Center(
child: new Text(
_active ? 'Active' : 'No Active',
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],
),
),
);
}
}
调用
void main() {
runApp(MyApp());
// runApp(Text("hellosjglajgl"));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home:Scaffold(
appBar: AppBar(
title: Text('Hello Flutter'),
),
body: TapboxA(),
)
);
}
}
效果图:

点击灰色色块,进行变色。
父Widget管理子Widget的状态
///------------------------- ParentWidgetState 类 ----------------------------------
///父组件
class ParentWidgetState extends StatefulWidget {
@override
_ParentWidgetState createState() => new _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidgetState> {
bool _active = false;
///回掉函数
void _handleTapboxChaned(bool newValue){
setState(() {
//修改状态
_active = newValue;
});
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Container(
child: new TapboxB (
active: _active,
//将_handleTapboxChaned函数赋值给TapboxB的onChanged
onChanged: _handleTapboxChaned,
),
);
}
}
///------------------------- TapboxB ----------------------------------
///子组件
class TapboxB extends StatelessWidget {
final bool active;
///定义接收父类回调函数的指针
final ValueChanged<bool> onChanged;
TapboxB({Key key, this.active: false, @required this.onChanged}) : super(key: key);
void _handleTap() {
onChanged(!active);
}
@override
Widget build(BuildContext context) {
return new GestureDetector(
//调用回调函数传值
onTap: _handleTap,
child: new Container(
child: new Center(
child: new Text(
active ? "Active【激活】" : "No Active【没激活】",
style: new TextStyle(
fontSize: 18.0,
color: Colors.white,
),
),
),
width: 200,
height: 200,
decoration: new BoxDecoration(
color: active ? Colors.lightGreen[700] : Colors.grey[600],
),
),
);
}
}
调用
void main() {
runApp(MyApp());
// runApp(Text("hellosjglajgl"));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home:Scaffold(
appBar: AppBar(
title: Text('Hello Flutter'),
),
body: ParentWidgetState(),
)
);
}
}
效果图:

网友评论