Flutter中的Key

Key本身是一个抽象类

LocalKey

static bool canUpdate(Widget oldWidget, Widget newWidget) {
    return oldWidget.runtimeType == newWidget.runtimeType
        && oldWidget.key == newWidget.key;
  }

用作diff算法的核心所在!用作Element和Widget进行比较!

  • ValueKey 以一个数据作为Key。如:数字、字符
  • ObjectKey以Object对象作为Key
  • UniqueKey可以保证Key的唯一性!(一旦使用Uniquekey那么就不存在Element复用 了!)

GlobalKey

  • GlobalKey可以获取到对应的Widget的State对象!
class GlobalKeyDemo extends StatelessWidget {
  final GlobalKey<_ChildPageState> _globalKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GlobalKeyDemoo'),
      ),
      body: ChildPage(
        key: _globalKey,
      ),
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            //在StatelessWidget中改变StatefulWidget里的内容并刷新UI
            _globalKey.currentState._count++;
            _globalKey.currentState.data =
                'old' + _globalKey.currentState._count.toString();
            _globalKey.currentState.setState(() {});
          }),
    );
  }
}

class ChildPage extends StatefulWidget {
  ChildPage({Key key}) : super(key: key);
  @override
  _ChildPageState createState() => _ChildPageState();
}

class _ChildPageState extends State {
  int _count = 0;
  String data = 'hello';

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          Text(_count.toString()),
          Text(data),
        ],
      ),
    );
  }
}

你可能感兴趣的:(Flutter中的Key)