Flutter尺寸测量插件measured的使用

Flutter尺寸测量插件measured的使用

简介

measured 插件允许你在每次子部件大小发生变化时显示实际的宽度和高度。这可以帮助我们检查屏幕布局或部件排列变化时大小的变化情况。同时,你还可以确定屏幕上合适的大小,并将其作为UX和UI设计的参考。此外,你还可以注册一个回调函数,在子部件大小改变时执行。

使用方法

在你的项目中添加以下导入语句:

import 'package:measured/measured.dart';

然后,你可以使用 Measured 组件来包装你想监控大小变化的子部件。例如:

final controller = AnimationController(vsync: this);
...
...
Measured(
  child: SizedBox(
    width: 100.0 + 50.0 * controller.value,
    height:100.0 + 50.0 * (1 - controller.value),
    child: Container(
      color: Colors.red,
    ),
  ),
)

// 或者使用 Widget 扩展
SizedBox(
    width: 100.0 + 50.0 * controller.value,
    height:100.0 + 50.0 * (1 - controller.value),
    child: Container(
      color: Colors.red,
    ),
  ).measured(
    borders: const [
      MeasuredBorder.right,
      MeasuredBorder.bottom,
    ],
    onChanged(
      () => {}
    ),
  )

参数

borders

  • 指定显示尺寸的位置(左、右、上、下)。
  • 如果不设置,默认值为 [MeasuredBorder.top, MeasuredBorder.left],即 MeasuredBorder.topleft

onChanged

  • 当子部件的大小发生变化时,执行已注册的回调函数。

outlined

  • 绘制一个矩形边框,该边框适应子部件的大小。

width, color

  • 测量线的线宽和颜色。

padding

  • 指定显示尺寸位置与边界的间距。

示例代码

以下是使用 measured 插件的完整示例代码:

import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:align_positioned/align_positioned.dart';

import 'package:measured/measured.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends HookWidget {
  const HomePage({super.key});

  static String title = 'Home';

  [@override](/user/override)
  Widget build(BuildContext context) {
    final length = useState('');
    final controller = useAnimationController();
    final align = useMemoized(() => controller.drive(
          AlignmentTween(begin: Alignment.topRight, end: Alignment.bottomLeft),
        ));
    useAnimation(align);

    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            AnimatedBuilder(
              animation: controller,
              builder: (context, child) {
                return Measured(
                  color: Colors.white,
                  style: const TextStyle(color: Colors.white, fontSize: 10.0),
                  child: Container(
                    width: 300.0 + 80.0 * controller.value,
                    height: 400.0 + 150.0 * controller.value,
                    decoration: const BoxDecoration(
                      color: Colors.red,
                    ),
                    child: Stack(
                      fit: StackFit.expand,
                      children: [
                        AlignPositioned(
                          alignment: align.value,
                          child: Transform.rotate(
                            angle: controller.value * 2 * pi,
                            child: Measured(
                              borders: MeasuredBorder.topLeft,
                              backgroundColor: Colors.green.withAlpha(120),
                              color: Colors.yellow,
                              width: 1.0,
                              style: const TextStyle(
                                  color: Colors.white,
                                  fontSize: 10.0,
                                  fontWeight: FontWeight.bold),
                              outlined: true,
                              onChanged: (size) {
                                length.value = size.toString();
                              },
                              child: SizedBox(
                                width: 150.0 + 100 * controller.value,
                                height: 100.0 + 100 * (1 - controller.value),
                                child: const FlutterLogo(),
                              ),
                            ),
                          ),
                        ),
                        AlignPositioned(
                          alignment: const Alignment(0.9, 0.8),
                          child: SizedBox(
                            width: 150.0 + 60.0 * (1 - controller.value),
                            height: 80.0 + 30.0 * (1 - controller.value),
                            child: const FlutterLogo(),
                          ).measured(
                            borders: MeasuredBorder.all,
                            width: 2.0,
                            backgroundColor: Colors.white.withOpacity(0.5),
                          ),
                        ),
                        AlignPositioned(
                          alignment: const Alignment(-0.9, -0.8),
                          child: SizedBox(
                            width: 50.0 + 60.0 * (1 - controller.value),
                            height: 40.0 + 30.0 * (1 - controller.value),
                            child: const FlutterLogo(),
                          ).measured(
                            borders: MeasuredBorder.none,
                            outlined: true,
                            width: 0.5,
                            backgroundColor: Colors.white.withOpacity(0.5),
                          ),
                        ),
                        AlignPositioned(
                          alignment: Alignment.center,
                          child: Text(
                            length.value.toString(),
                            style: const TextStyle(
                              fontSize: 24.0,
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          if (controller.isAnimating) {
            controller.stop();
          } else {
            controller.repeat(
              reverse: true,
              period: const Duration(seconds: 1),
            );
          }
        },
        child: Icon(
          controller.isAnimating ? Icons.pause : Icons.play_arrow_rounded,
        ),
      ),
    );
  }
}

更多关于Flutter尺寸测量插件measured的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter尺寸测量插件measured的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用measured插件进行尺寸测量的代码示例。measured插件允许你在Flutter应用中测量Widget的尺寸,这在某些布局调整或动态内容显示时非常有用。

首先,确保你已经在pubspec.yaml文件中添加了measured依赖:

dependencies:
  flutter:
    sdk: flutter
  measured: ^x.y.z  # 请替换为最新的版本号

然后运行flutter pub get来安装依赖。

接下来是一个简单的示例,展示如何使用measured插件来测量一个Widget的尺寸:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Measured Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Measured Example'),
        ),
        body: Center(
          child: MeasuredBuilder(
            builder: (context, size) {
              // 在这里,size包含了被测量Widget的尺寸
              print('Measured Widget Size: ${size.width} x ${size.height}');
              return Container(
                color: Colors.blue,
                child: Center(
                  child: Text(
                    'Size: ${size.width.toInt()} x ${size.height.toInt()}',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
                width: 200,
                height: 200,
              );
            },
            child: Container(
              color: Colors.blue.withOpacity(0.5), // 半透明背景以便观察尺寸测量效果
            ),
          ),
        ),
      ),
    );
  }
}

代码解释:

  1. 依赖添加:确保在pubspec.yaml中添加了measured依赖。
  2. MeasuredBuilder:使用MeasuredBuilder包装你想要测量的Widget。MeasuredBuilderbuilder回调提供了两个参数:BuildContext和被测量Widget的Size
  3. 打印尺寸:在builder回调中,你可以使用size对象获取被测量Widget的宽度和高度,这里我们简单地打印出来。
  4. 显示尺寸:为了可视化效果,我们在被测量的Container中显示其尺寸。注意,这里我们用了另一个Container作为MeasuredBuilderchild,但它仅用于视觉效果,实际的测量是基于builder回调中的Widget。

这个示例展示了如何使用measured插件来动态获取Widget的尺寸并在应用中加以利用。你可以根据需要调整Widget的结构和样式。

回到顶部