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),
    );
  }
相关推荐
helloxmg3 小时前
鸿蒙harmonyos next flutter通信之MethodChannel获取设备信息
flutter
helloxmg3 小时前
鸿蒙harmonyos next flutter混合开发之开发package
flutter·华为·harmonyos
lqj_本人1 天前
flutter_鸿蒙next_Dart基础②List
flutter
lqj_本人1 天前
flutter_鸿蒙next_Dart基础①字符串
flutter
The_tuber_sadness1 天前
【Flutter】- 基础语法
flutter
helloxmg1 天前
鸿蒙harmonyos next flutter通信之BasicMessageChannel获取app版本号
flutter
linpengteng2 天前
使用 Flutter 开发数字钱包应用(Dompet App)
前端·flutter·firebase
云兮Coder2 天前
鸿蒙 HarmonyNext 与 Flutter 的异同之处
flutter·华为·harmonyos