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),
      ),
    );
  }
}
相关推荐
扶风ff6 小时前
新品知识更新太快?用练题簿在线刷题,安排企业培训的小测与复盘
前端·学习·小程序
对空六课7 小时前
支持注意力分析的热力图工具有哪些?
前端·数据库·数据分析
Csvn8 小时前
Vue3 响应式与编译:依赖收集如何升级为节点级靶向更新
前端
星栈9 小时前
pnpm 12 升级实测
前端·javascript
Sirens.9 小时前
Java并发锁详解:六类锁策略与 synchronized 底层原理
java·前端·算法
特创数字科技10 小时前
一个纯本地运行的图片处理工具:压缩 / 裁剪 / 九宫格 / 圆角 / 滤镜 / 拼图 / 水印,终生使用
前端
IT_陈寒11 小时前
Vue的v-if和v-for混用居然是个天坑
前端·人工智能·后端
天衍四九-11 小时前
【无标题】
前端·spring boot·mysql·nginx·docker
广州华水科技11 小时前
2026年单北斗GNSS变形监测系统推荐榜单,解锁GNSS位移监测新高度
前端
xcyxiner11 小时前
DicomViewer24 修复编译bug(window test 失败)
前端·qt