前言
在Flutter开发中,状态管理是构建用户界面的关键部分。尤其是在涉及组件重建、屏幕旋转等情况时,确保组件状态的一致性显得尤为重要。本文档将探讨Flutter中定时器的使用方法,以及如何通过不同类型的Key(如LocalKey和GlobalKey)来有效管理状态。
定时器
void initState() { super.initState(); Timer.periodic(Duration(seconds: 2), (timer) { print("hello3"); });}
import 'dart:async'; import 'package:flutter/material.dart'; class CountdownPage extends StatefulWidget { @override _CountdownPageState createState() => _CountdownPageState(); } class _CountdownPageState extends State<CountdownPage> { late Timer _timer; int _secondsRemaining = 60; @override void initState() { super.initState(); startTimer(); } void startTimer() { const oneSec = const Duration(seconds: 1); _timer = Timer.periodic( oneSec, (timer) { setState(() { if (_secondsRemaining < 1) { _timer.cancel(); } else { _secondsRemaining--; } }); }, ); } String formatTime(int seconds) { int minutes = (seconds / 60).truncate(); int remainingSeconds = seconds - (minutes * 60); String minutesStr = minutes.toString().padLeft(2, '0'); String secondsStr = remainingSeconds.toString().padLeft(2, '0'); return '$minutesStr:$secondsStr'; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Countdown Page'), ), body: Center( child: Text( formatTime(_secondsRemaining), style: TextStyle( fontSize: 48, fontWeight: FontWeight.bold, ), ), ), ); } @override void dispose() { _timer.cancel(); super.dispose(); } } void main() { runApp(MaterialApp( home: CountdownPage(), )); }
通过key 来 操作状态
localKey
local key 有 三种
valueKey,uniqueKey,Object(不常用)
valueKey("string") // 里面 放 值 组件里面不 可以 放相同的值 uniqueKey () // 加上 即可 自动 生成 值 key : ...key
List<Widget> list = [ Box( key: ValueKey("1"), // key: ValueKey("2"), color: Colors.red, ), Box( // 自动 生产 不添加 参数 // key: UniqueKey(), key: ValueKey("2"), color: Colors.green, ), Box( // 不常用 // key: ObjectKey(new Box(color: Colors.grey)), key: ValueKey("3"), color: Colors.blue, ), ];
屏幕旋转 bug
屏幕旋转
// 屏幕旋转 方向 // print(MediaQuery.of(context).orientation); // Orientation.landscape 竖向 // Orientation.portrait 横向
body: Center( child: MediaQuery.of(context).orientation == Orientation.portrait ? Column( mainAxisAlignment: MainAxisAlignment.center, children: list, ) : Row( mainAxisAlignment: MainAxisAlignment.center, children: list, )),
组件类型 不一致 状态 丢失
配置全局 的key
GlobalKey _globalKey1 = GlobalKey(); GlobalKey _globalKey2 = GlobalKey(); GlobalKey _globalKey3 = GlobalKey(); List<Widget> list = []; @override void initState() { super.initState(); list = [ Box( key: _globalKey1, color: Colors.red, ), Box( key: _globalKey2, color: Colors.green, ), Box( key: _globalKey3, color: Colors.blue, ), ]; }
import 'package:flutter/material.dart'; class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) { return MaterialApp( title: "flutter,title", home: homePage(), ); } } class homePage extends StatefulWidget { const homePage({Key? key}) : super(key: key); @override State<homePage> createState() => _homePageState(); } class _homePageState extends State<homePage> { GlobalKey _globalKey1 = GlobalKey(); GlobalKey _globalKey2 = GlobalKey(); GlobalKey _globalKey3 = GlobalKey(); List<Widget> list = []; @override void initState() { super.initState(); list = [ Box( key: _globalKey1, color: Colors.red, ), Box( key: _globalKey2, color: Colors.green, ), Box( // 不常用 // key: ObjectKey(new Box(color: Colors.grey)), key: _globalKey3, color: Colors.blue, ), ]; } @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { // 打乱 list setState(() { list.shuffle(); }); }, child: Icon(Icons.refresh), ), appBar: AppBar( title: Text("hello,title"), ), body: Center( child: MediaQuery.of(context).orientation == Orientation.portrait ? Column( mainAxisAlignment: MainAxisAlignment.center, children: list, ) : Row( mainAxisAlignment: MainAxisAlignment.center, children: list, )), ); } } class Box extends StatefulWidget { final Color color; // a : b // key 可选 参数 const Box({Key? key, required this.color}) : super(key: key); @override State<Box> createState() => _BoxState(); } class _BoxState extends State<Box> { late int _count = 0; // 按钮 的 属性 设置 @override Widget build(BuildContext context) { return ElevatedButton( style: ButtonStyle(backgroundColor: MaterialStateProperty.all(widget.color)), onPressed: () { setState(() { _count++; }); }, child: Text( "$_count", style: Theme.of(context).textTheme.headlineMedium, ), ); } } void main() { runApp(const MyApp()); }
currentState
父组件 管理 子 组件
在 父 widget 中 配置 全局key
GlobalKey _globalKey1 = GlobalKey();
调用 box 并且 绑定 key
body: Center( child: Box( key: _globalKey1, color: Colors.red, ), ));
通过 方法 获取 相关 属性
onPressed: () { //document.getById(...) // 获取 子组件 的属性 var boxState = _globalKey1.currentState as _BoxState; setState(() { boxState._count++; print(boxState._count); boxState.run(); }); },
late int _count = 0; void run() { print("running = ${_count}"); }