Flutter 扩展函数项目实用之封装SizedBox

Flutter里扩展函数可以用简化代码写法,关键字为extension,伪代码写法如下:

extension 扩展类名 on 扩展类型 {
//扩展方法
}

在Flutter页面里实现控件间距会常用到SizedBox,可使用扩展函数封装来达到简化代码的目的,基本步骤如下:

1、创建num_extension.dart文件,扩展类名为SizedBox+类型Double+后缀Extension,代码如下:

Dart 复制代码
import 'package:flutter/material.dart';

extension SizedBoxDoubleExtension on double {
  SizedBox get width => SizedBox(width: this);
  SizedBox get height => SizedBox(height: this);
  SizedBox withHeight(double height) => SizedBox(width: this, height: height);
}

2、使用示例对照,节选代码如下:

Dart 复制代码
  ///此为不使用扩展函数的写法
  Widget _buildRow() {
    return Row(
      children: [
        _buildText("1"),
        const SizedBox(
          width: 10,
        ),
        _buildText("2"),
        const SizedBox(
          width: 10,
        ),
        _buildText("3"),
      ],
    );
  }

  ///此为使用扩展函数的写法,要简洁些
  Widget _buildRowExtension() {
    return Row(
      children: [
        _buildText("1"),
        10.0.width,
        _buildText("2"),
        10.0.width,
        _buildText("3"),
      ],
    );
  }

  Widget _buildText(String text) {
    return Text(
      text,
      style: const TextStyle(color: Colors.blue),
    );
  }
相关推荐
月光下的丝瓜4 小时前
Flutter 国内安装指南
前端·flutter
恋猫de小郭3 天前
Amper 正式转正 Kotlin Toolchain ,Gradle 未来何去何从
android·前端·flutter
张风捷特烈3 天前
Flutter 类库大揭秘#02 | path_provider 各平台实现
前端·flutter
TT_Close3 天前
别劝退了!5秒搞定 Flutter 鸿蒙 FVM 起跑线
flutter·harmonyos·visual studio code
你听得到114 天前
用户说 App 卡,但说不清在哪?我把 Flutter 监控 SDK 升级成了链路观测工作台
前端·flutter·性能优化
stringwu5 天前
Flutter 开发必备:MVI 架构的高效实现指南
前端·flutter
程序员老刘6 天前
Flutter版本选择指南:3.44系列继续观望 | 2026年6月
flutter·ai编程·客户端
用户965597361908 天前
Provider vs Bloc vs GetX vs Riverpod:Flutter 状态管理方案怎么选?
flutter
恋猫de小郭8 天前
Flutter Patchwork,不用 Fork 改依赖包源码的第三方工具
android·前端·flutter
程序员老刘8 天前
跑分第一的编程大模型,我为啥不用?
flutter·ai编程·vibecoding