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),
    );
  }
相关推荐
大龄秃头程序员6 小时前
一次 Flutter 动画 Demo 的整理与复盘
flutter
AlexMaybeBot9 小时前
躺在沙发上开发 Openclaw 的移动端APP
前端·flutter
天空之城--10 小时前
Android Flutter行业动态与学习参考(2026年8月)
android·flutter
FungLeo11 小时前
Flutter Web token 存储陷阱:crypto.subtle 在非安全上下文失效排查实录
前端·安全·flutter
FungLeo11 小时前
Flutter Web 中文字体困境与渲染器选择:CanvasKit vs HTML renderer 实战
前端·flutter·html
杉氧12 小时前
原生交互:如何在 Flutter 中嵌入 Android/iOS 原生组件并解决手势冲突
android·flutter·dart
恋猫de小郭13 小时前
Flutter iOS Deep Link 为什么会突然失效:一系列难以言喻的问题
android·前端·flutter
FungLeo1 天前
Flutter fl_chart 0.70 破坏性 API 迁移实录:duration/getTooltipColor/withValues 全解
flutter·fl_chart
FungLeo1 天前
Flutter 吸顶分组列表实战:语义桶分组 + 点击头平滑滚动
android·flutter
FungLeo1 天前
Flutter 超长 StatefulWidget 拆分术:part of + extension on State 实战
android·flutter·dart