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),
    );
  }
相关推荐
spmcor4 小时前
Flutter 学习笔记 (3):布局初探 —— Row、Column、Stack 与 Container
flutter
风华圆舞5 小时前
DevEco Studio 和 Flutter 工具链如何协同工作
flutter·华为·架构·harmonyos
朱莉^_^JuneLee5 小时前
Flutter 性能优化实战:用 ConsumerWidget + select 做到真正的局部刷新
flutter
G_dou_8 小时前
Flutter三方库适配OpenHarmony【palindrome_checker】回文检测器项目完整实战
flutter·harmonyos
朱莉^_^JuneLee9 小时前
Flutter 模块化架构实战:用 Barrel Export 管控模块边界
flutter·架构
风华圆舞10 小时前
鸿蒙导航意图 的 Flutter 侧封装思路
flutter·华为·harmonyos
风华圆舞10 小时前
Flutter 调用原生失败时,如何优雅处理 `MissingPluginException`
flutter·华为·harmonyos
风华圆舞10 小时前
鸿蒙防窥保护 的 Flutter 侧封装思路
flutter·华为·harmonyos
风华圆舞11 小时前
SpeechRecognitionChannel 的 Flutter 侧封装思路
flutter·华为·harmonyos