import 'package:flutter/material.dart';
class ColorItem {
GlobalKey key;
Color color;
//设置子组件的key,这里用的GlobalKey,用来后面获取子组件
//如果不用获取子组件,也可以用Valuekey
ColorItem({required this.color}) : key = GlobalKey();
}
class FlutterKey extends StatefulWidget {
const FlutterKey({super.key});
@override
State<FlutterKey> createState() => _FlutterKeyState();
}
class _FlutterKeyState extends State<FlutterKey> {
List<ColorItem> colorList = [
ColorItem(color: Colors.cyan),
ColorItem(color: Colors.pink),
ColorItem(color: Colors.indigo),
ColorItem(color: Colors.deepOrangeAccent),
];
List<Widget> colorContainer() {
return colorList.map((color) {
return ColorBox(
color: color.color,
key: color.key,
);
}).toList();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('FLutterKey'),
),
body: SizedBox(
width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: colorContainer(),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
for (var color in colorList) {
//通过GlobalKey 的 key.currentState 获取子组件,能直接更新子组件的状态,调用子组件的方法
var state = color.key.currentState as _ColorBoxState;
setState(() {
state.num = 0;
});
}
});
},
child: const Icon(Icons.refresh),
));
}
}
class ColorBox extends StatefulWidget {
final Color color;
const ColorBox({Key? key, required this.color}) : super(key: key);
@override
State<ColorBox> createState() => _ColorBoxState();
}
class _ColorBoxState extends State<ColorBox> {
int num = 0;
@override
Widget build(BuildContext context) {
return Container(
width: 60,
height: 60,
decoration: BoxDecoration(
color: widget.color,
borderRadius: BorderRadius.circular(5),
),
// decoration: BoxDecoration(borderRadius: BorderRadius.circular(5)),
margin: const EdgeInsets.only(bottom: 10),
child: Center(
child: TextButton(
onPressed: () {
setState(() {
num++;
});
},
child: Text(
num.toString(),
style: const TextStyle(color: Colors.white),
),
),
),
);
}
}
标签:const,key,color,Key,组件,ColorItem,Flutter
From: https://www.cnblogs.com/angelwgh/p/17918823.html