美文网首页
Flutter详解 Key

Flutter详解 Key

作者: 致青春_bf42 | 来源:发表于2020-11-13 15:11 被阅读0次

    Key 是什么

    key是用来作为WidgetElementSemanticsNode的标示,仅仅用来更新widget->key相同的小部件的状态

    Key子类包含LocalKeyGlobalKey

    LocalKey

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

    abstract class LocalKey extends Key {
      const LocalKey() : super.empty();
    }
    

    LocalKey子类包含ValueKey/ObjectKey/UniqueKey

    • ValueKey 以一个数据作为Key。如:数字、字符
     StfulItem(
          'aaaaa',
          key: ValueKey(111),
        ),
    
    • ObjectKeyObject对象作为Key
        StfulItem(
          'bbbbb',
          key: ObjectKey(Text('222')),
        ),
    
    • UniqueKey可以保证Key的唯一性!(一旦使用Uniquekey那么就不存在Element复用 了!)
      StfulItem(
          'ccccc',
          key: UniqueKey(),
        ),
    

    具体代码如下

    import 'dart:math';
    
    import 'package:flutter/material.dart';
    
    class KeyDemo extends StatefulWidget {
      @override
      _KeyDemoState createState() => _KeyDemoState();
    }
    
    class _KeyDemoState extends State<KeyDemo> {
      List<Widget> items = [
        StfulItem(
          'aaaaa',
          key: ValueKey(111),
        ),
        StfulItem(
          'bbbbb',
          key: ObjectKey(Text('222')),
        ),
        StfulItem(
          'ccccc',
          key: UniqueKey(),
        ),
      ];
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('keyDemo'),
          ),
          body: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: items,
          ),
          floatingActionButton: FloatingActionButton(
            child: Icon(Icons.add),
            onPressed: () {
              setState(() {
                items.removeAt(0);
              });
            },
          ),
        );
      }
    }
    
    class StfulItem extends StatefulWidget {
      final title;
      StfulItem(this.title, {Key key}) : super(key: key);
    
      @override
      _StfulItemState createState() => _StfulItemState();
    }
    
    class _StfulItemState extends State<StfulItem> {
      final _color = Color.fromRGBO(
          Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1.0);
      @override
      Widget build(BuildContext context) {
        return Container(
          width: 100,
          height: 100,
          color: _color,
          child: Text(widget.title),
        );
      }
    }
    
    //做一个正方形!
    class StlItem extends StatelessWidget {
      final title;
      StlItem(this.title);
      final _color = Color.fromRGBO(
          Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1.0);
      @override
      Widget build(BuildContext context) {
        return Container(
          width: 100,
          height: 100,
          color: _color,
          child: Text(title),
        );
      }
    }
    
    

    GlobalKey

    GlobalKey可以获取到对应的WidgetState对象!关于stateFul尽量在末端!在树的"叶子"处
    具体代码如下

    import 'package:flutter/material.dart';
    
    class GlobalKeyDemo extends StatelessWidget {
      final GlobalKey<_ChildPageState> _globalKey = GlobalKey();
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('GlobalKeyDemo'),
          ),
          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();
    }
    
    class _ChildPageState extends State<ChildPage> {
      int count = 0;
      String data = 'hello';
      @override
      Widget build(BuildContext context) {
        return Center(
          child: Column(
            children: <Widget>[
              Text(count.toString()),
              Text(data),
            ],
          ),
        );
      }
    }
    
    

    相关文章

      网友评论

          本文标题:Flutter详解 Key

          本文链接:https://www.haomeiwen.com/subject/mjypbktx.html