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),
      ),
    );
  }
}
相关推荐
bug总结3 小时前
uniapp vue3全局方法注册使用
前端·javascript·uni-app
华无丽言4 小时前
如何在宜搭中实现获取子表中的字段值赋值到父表中?
前端·javascript·低代码
IT_陈寒4 小时前
Vue的computed属性竟然坑了我一把
前端·人工智能·后端
威斯软科的老司机4 小时前
通俗讲解 CNN 图像识别、向量 Embedding、Softmax 概率计算这三块的简化原理
前端·人工智能·ui·数字孪生
泯泷5 小时前
手搓JSVM第 12 篇:完整最小 JSVM 实现与源码设计复盘
前端·javascript·前端框架
默_笙5 小时前
🍔 给 AI 发一张结构化表格(下):从"自由发挥"到"按格填空"的输出驯服指南
前端·javascript
泯泷5 小时前
手搓JSVM第 11 篇:打包、模块与 CLI:把 VM 产物变成可运行文件
前端·javascript·前端框架
泯泷5 小时前
手搓JSVM第 10 篇:对象、数组与属性访问
前端·javascript·前端框架
泯泷6 小时前
手搓JSVM第 9 篇:闭包:函数如何记住外部变量
前端·javascript·前端框架
晴天166 小时前
前端 SSR、BFF 原理介绍
前端·javascript·网络·html