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),
    );
  }
相关推荐
tbit6 小时前
Android Google Map PlatformView 图层异常排查与修复
flutter
哈__6 小时前
Flutter 3.44.9 + OpenHarmony7:home_widget 三方库桌面服务卡片(FormKit)的应用
flutter·华为·harmonyos
哈__8 小时前
Flutter 3.44.9 + OpenHarmony7:image_cropper三方库 图片裁剪的应用
flutter·openharmony
淡写成灰1 天前
「Flutter 文件保存太难了?」一个插件打通 7 大平台,我把方案开源了 🎉
flutter·harmonyos
坚果的博客1 天前
Flutter 三方库 phone_state 的 OpenHarmony 适配实战
flutter
ljt27249606611 天前
Flutter笔记--本地通知
笔记·flutter
lqj_本人1 天前
Flutter 三方库 Pedometer 的鸿蒙化适配指南
flutter·华为·harmonyos
Android-Flutter2 天前
flutter GetX 详解
android·flutter
坚果的博客2 天前
Flutter OHOS 环境搭建实战:oh-3.44.9-dev 从 0 到 1 完整记录
flutter·华为·harmonyos
Crazy_MT2 天前
Android Studio 运行 Flutter iOS 真机白屏,但 Xcode 和命令行正常的排查记录
flutter·android studio