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












相关文章
|
Dart 索引
flutter key 详解
flutter key 详解
152 0
flutter key 详解
|
XML Java Android开发
Flutter | Key的原理和使用(上)
Flutter | Key的原理和使用(上)
Flutter | Key的原理和使用(上)
|
Android开发 容器
Flutter | Key的原理和使用(下)
Flutter | Key的原理和使用(下)
|
存储 Android开发 iOS开发
【Flutter Widget】Flutter移动UI框架使用Material和密匙Key的具体在项目里的实战经验
【Flutter Widget】Flutter移动UI框架使用Material和密匙Key的具体在项目里的实战经验
|
9天前
|
Android开发 iOS开发 容器
鸿蒙harmonyos next flutter混合开发之开发FFI plugin
鸿蒙harmonyos next flutter混合开发之开发FFI plugin
|
4月前
|
开发框架 前端开发 测试技术
Flutter开发常见问题解答
Flutter开发常见问题解答
|
19天前
|
开发框架 移动开发 Android开发
安卓与iOS开发中的跨平台解决方案:Flutter入门
【9月更文挑战第30天】在移动应用开发的广阔舞台上,安卓和iOS两大操作系统各自占据半壁江山。开发者们常常面临着选择:是专注于单一平台深耕细作,还是寻找一种能够横跨两大系统的开发方案?Flutter,作为一种新兴的跨平台UI工具包,正以其现代、响应式的特点赢得开发者的青睐。本文将带你一探究竟,从Flutter的基础概念到实战应用,深入浅出地介绍这一技术的魅力所在。
55 7
|
5月前
|
前端开发 C++ 容器
Flutter-完整开发实战详解(一、Dart-语言和-Flutter-基础)(1)
Flutter-完整开发实战详解(一、Dart-语言和-Flutter-基础)(1)
|
1月前
|
JSON Dart Java
flutter开发多端平台应用的探索
flutter开发多端平台应用的探索
43 6
|
1月前
|
JSON Dart Java
flutter开发多端平台应用的探索 下 (跨模块、跨语言通信之平台通道)
flutter开发多端平台应用的探索 下 (跨模块、跨语言通信之平台通道)