Flutter (二十二) GlobalKey

GlobalKey

通过给一个组件设置GlobalKey,则可以在任意位置对该组件进行操作。

比如让获取某个组件的位置信息,滚动到可见区域。

scala 复制代码
import 'dart:math' show Random;

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final GlobalKey<_ChildWidgetState> _redKey = GlobalKey<_ChildWidgetState>();
  final GlobalKey<_ChildWidgetState> _blueKey = GlobalKey<_ChildWidgetState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('EasyRefresh 示例')),
      body: Container(
        color: Colors.amber,
        child: ListView(
          children: [
            ChildWidget(
              key: _redKey,
              color: Colors.red,
              title: "红色",
              actionKey: _blueKey,
            ),
            SizedBox(height: MediaQuery.of(context).size.height),
            ChildWidget(
              key: _blueKey,
              color: Colors.blue,
              title: "蓝色",
              actionKey: _redKey,
            ),
          ],
        ),
      ),
    );
  }
}

class ChildWidget extends StatefulWidget {
  Color _color;
  final String _title;
  final GlobalKey<_ChildWidgetState> _actionKey;
  ChildWidget({
    super.key,
    required this._color,
    required this._title,
    required this._actionKey,
  });

  @override
  _ChildWidgetState createState() => _ChildWidgetState();
}

class _ChildWidgetState extends State<ChildWidget> {
  void changeToColor(Color color) {
    setState(() {
      widget._color = color;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: widget._color,
      height: 100,
      alignment: Alignment.center,
      child: GestureDetector(
        onTap: () {
          Color color = HSLColor.fromAHSL(
            1,
            Random().nextInt(360).toDouble(),
            0.5,
            0.5,
          ).toColor();
          widget._actionKey.currentState?.changeToColor(color);
          print('点击了');
          final buildContext = widget._actionKey.currentContext;
          if (buildContext != null) {
            ScaffoldMessenger.of(
              buildContext,
            ).showSnackBar(const SnackBar(content: Text('改变了对方颜色')));

            final renderBox = buildContext.findRenderObject() as RenderBox?;

            final size = renderBox!.size; // 对方的尺寸
            final offset = renderBox!.localToGlobal(Offset.zero); // 对方在屏幕的坐标
            print('对方尺寸: $size, 屏幕坐标: $offset');

            Scrollable.ensureVisible(
              buildContext,
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeInOut,
            );
          }
        },
        child: Text(widget._title),
      ),
    );
  }
}
相关推荐
Hilaku1 小时前
2027 制药行业 ERP 系统架构选型笔记:从 GMP 合规追溯到动态 MCP 接入
前端·javascript·程序员
掘金安东尼2 小时前
人工智能AI
前端
kyriewen2 小时前
AI 面试官筛前端简历,先出局的不是写代码慢的
前端·面试·程序员
BigTopOne3 小时前
10 引用与借用:& 和 &mut
前端
粥里有勺糖3 小时前
视野修炼-技术周刊第139期 | AI 不会让时间变多
前端·github·ai编程
ZJPRENO4 小时前
WorkBuddy 从零到一|混元4 Flash 实战手记-提醒小工具开发
前端
用户302822530684 小时前
AI 视频图片运镜为什么会抖?帧率拉高也救不了多次取整
前端·人工智能·typescript
前端码农人生4 小时前
前端转 Agent:真正要重写的不是接口层,是交互层
前端
孟陬5 小时前
Foobar 技术周刊 #003:黄仁勋的三段吃瓜和回归,抛开事实不谈(嘿嘿)让全人类 AGI 进程得以继续
前端·后端·程序员
涛涛ing5 小时前
别再用 AI 写计算逻辑了:你的页面卡死,连鼠标都点不动
前端