Key
Key 本身是一个抽象类
- LocalKey:用作diff算法的核心所在,用作Element和Widget进行比较!
- ValueKey :以一个数据作为key,例如数字、字符
- ObjectKey :以Object对象作为key
- UniqueKey:可以保证key的唯一性!(一旦使用UniqueKey,那么就不存在Element复用了)
- GlobalKey:可以获取到对应的Widget的State对象!
class GlobalKeyDemo extends StatelessWidget {
final GlobalKey<_ChildPageState> _globalKey = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: ChildPage(key: _globalKey),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
_globalKey.currentState.data =
'old:' +_globalKey.currentState.count.toString();
_globalKey.currentState.count ++;
_globalKey.currentState.setState(() { });
},
),
);
}
}
class ChildPage extends StatefulWidget {
ChildPage({Key key}) : super(key: key);
@override
_ChildPageState createState() => _ChildPageState();
}
网友评论