//子元素状态不更新 需要添加key,理解为vue的key
Flutter key子类包含 LocalKey 和 GlobalKey 。
//局部键(LocalKey):ValueKey、ObjectKey、UniqueKey
const Box({Key? key, required this.color}):super(key:key);
//传递key
Box(color: Colors.green,key:ValueKey(3)),
Box(color: Colors.green,key:UniqueKey()), //UniqueKey() 唯一值 每次都会随机生成
Box(color: Colors.green,key:ObjectKey(Box(color:Colors.green))), //ObjectKey(Box(color:Colors.green)) 对象key,必须传递一个对象
// 全局键(GlobalKey): GlobalKey、GlobalObjectKey
GlobalKey _globalKey=GlobalKey()
GlobalObjectKey _globalKey=GlobalObjectKey(Box(color:Colors.green)))
//获取子组件的状态和属性
var gstate= _globalKey.currentSate as _BoxState //获取子组件的状态 调用子组件的属性 as _BoxState强制转换为子组件类型
print(gstate.属性/方法) gstate._count++;//获取子组件的状态并进行操作
var gWidget= _globalKey.currentWidget as Box //可以子widget as Box强制转换为子组件类型
print(gWidget.属性/方法)
var renderBox= (_globalKey.currentContext!.findRenderObject() as RenderBox); //可以获取渲染的属性 as RenderBox强制转换为子组件类型
print(gWidget.属性/方法)
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(title: 'contaniner', home: MyAPP()),
);
}
class MyAPP extends StatefulWidget {
const MyAPP({super.key});
@override
State<MyAPP> createState() => _MyAPPState();
}
class _MyAPPState extends State<MyAPP> {
final GlobalKey _globalKey = GlobalKey();
List<Widget> list = [];
@override
void initState() {
super.initState();
list = [
Box(color: Colors.red, key: _globalKey),
Box(color: Colors.yellow, key: ValueKey(2)),
Box(color: Colors.green, key: ValueKey(3)),
];
}
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
var gstate = _globalKey.currentState as _BoxState;
print(gstate);
gstate.run();
setState(() {
gstate._count++; // 将 body修改为 Box(color: Colors.red, key: _globalKey) 生效
print(gstate._count);
});
}, //执行方法
tooltip: 'Increment', // 提示
child: const Icon(Icons.refresh), //按钮文案
),
appBar: AppBar(
title: const Center(child: Text('PageViewSwiper1')),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: list,
),
),
);
}
}
class Box extends StatefulWidget {
final Color color;
Box({super.key, required this.color});
@override
State<Box> createState() => _BoxState();
}
class _BoxState extends State<Box> {
int _count = 0;
run() {
_count++;
}
@override
Widget build(BuildContext context) {
return SizedBox(
width: 100,
height: 100,
child: ElevatedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all(
RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
),
backgroundColor: MaterialStateProperty.all(widget.color),
),
onPressed: () => setState(() => _count++),
child: Text(
"$_count",
style: Theme.of(context).textTheme.headlineLarge,
),
),
);
}
}