1、什么是key
Widget中有个可选属性key,顾名思义,它是组件的标识符,当设置了key,组件更新时会根据新老组件的key是否相等来进行更新,可以提高更新效率。但一般我们不会去设置它,除非对某些具备状态且相同的组件进行添加、移除、或者排序时,就需要使用到key,不然就会出现一些莫名奇妙的问题。
例如下面的demo:
import 'dart:math';
import 'package:flutter/material.dart';
void main() {runApp(const MyApp());
}
class MyApp extends StatelessWidget {const MyApp({Key? key}) : super(key: key);@overrideWidget build(BuildContext context) {return MaterialApp(title: 'test',home: Scaffold(appBar: AppBar(title: const Text('key demo'),),body: const KeyDemo(),),);}
}
class KeyDemo extends StatefulWidget {const KeyDemo({Key? key}) : super(key: key);@overrideState<StatefulWidget> createState() => _KeyDemo();
}
class _KeyDemo extends State<KeyDemo> {final List<ColorBlock> _list = [const ColorBlock(text: '1'),const ColorBlock(text: '2'),const ColorBlock(text: '3'),const ColorBlock(text: '4'),const ColorBlock(text: '5'),];@overrideWidget build(BuildContext context) {return Column(children: [..._list,ElevatedButton(onPressed: () {_list.removeAt(0);setState(() {});},child: const Text('删除'),)],);}
}
class ColorBlock extends StatefulWidget {final String text;const ColorBlock({Key? key, required this.text}) : super(key: key);@overrideState<StatefulWidget> createState() => _ColorBlock();
}
class _ColorBlock extends State<ColorBlock> {final color = Color.fromRGBO(Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1.0);@overrideWidget build(BuildContext context) {