flutter:定时器&通过key操作状态 (十二)

简介: 本文档介绍了Flutter中的定时器使用方法、通过key操作状态的几种方式,包括localKey和GlobalKey的使用场景与示例代码,以及如何处理屏幕旋转导致的组件状态丢失问题。通过配置全局key,可以有效地管理父子组件之间的状态交互,确保在屏幕旋转等情况下保持组件状态的一致性。

前言

在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}");
  }












相关文章
|
5月前
|
Java Android开发
Android系统 获取用户最后操作时间回调实现和原理分析
Android系统 获取用户最后操作时间回调实现和原理分析
148 0
|
存储 Dart 数据库
重识Flutter状态管理 — 探索Flutter中的状态
我遇到过很多没有了解过响应式编程框架的,或者从事后端开发,自己想用Flutter写个app玩玩的朋友,一上来,不管在哪里都用`setState`,我问为啥不用状态管理,大部分都回了一句:啥是状态管理?
|
3月前
|
存储 API Android开发
kotlin开发安卓app,使用webivew 触发 onShowFileChooser, 但只能触发一次,第二次无法触发,是怎么回事。 如何解决
在Android WebView开发中,`onShowFileChooser`方法用于开启文件选择。当用户只能选择一次文件可能是因为未正确处理选择回调。解决此问题需确保:1) 实现`WebChromeClient`并覆写`onShowFileChooser`;2) 用户选择文件后调用`ValueCallback.onReceiveValue`传递URI;3) 传递结果后将`ValueCallback`设为`null`以允许再次选择。下面是一个Kotlin示例,展示如何处理文件选择和结果回调。别忘了在Android 6.0+动态请求存储权限,以及在Android 10+处理分区存储。
|
5月前
Qt6学习笔记十一(计时器事件)
Qt6学习笔记十一(计时器事件)
72 0
Qt6学习笔记十一(计时器事件)
|
12月前
|
监控 Go
Go 语言一次性定时器使用方式和实现原理
Go 语言一次性定时器使用方式和实现原理
65 0
|
存储 JavaScript 前端开发
web前端面试高频考点——Vue3.x升级的重要功能(emits属性、生命周期、多事件、Fragment、移出.async、异步组件写法、移出 filter、Teleport、Suspense...)
web前端面试高频考点——Vue3.x升级的重要功能(emits属性、生命周期、多事件、Fragment、移出.async、异步组件写法、移出 filter、Teleport、Suspense...)
222 0
|
Dart Android开发 开发者
Flutter Tips 小技巧(更新中)(下)
Flutter Tips 小技巧(更新中)(下)
377 0
Flutter Tips 小技巧(更新中)(下)
|
缓存 算法 安全
Sentinel-Go 源码系列(三)滑动时间窗口算法的工程实现
要说现在工程师最重要的能力,我觉得工程能力要排第一。 就算现在大厂面试经常要手撕算法,也是更偏向考查代码工程实现的能力,之前在群里看到这样的图片,就觉得很离谱(大概率是假的~)。
293 0
Sentinel-Go 源码系列(三)滑动时间窗口算法的工程实现
|
移动开发 开发工具 git
Flutter Tips 小技巧(更新中)(中)
Flutter Tips 小技巧(更新中)(中)
227 0