Flutter嵌套深?扩展函数了解一下,android面试题解析

本文介绍了如何使用Flutter中的扩展函数来解决嵌套过深的问题,通过示例展示了如何定义和使用扩展函数,使得代码更加简洁、易读。同时,文章强调了在移动开发中掌握这种技巧的重要性,特别是在面试和实际项目中。
摘要由CSDN通过智能技术生成

实际上从dart 2.6.0就开始支持扩展函数了

如果pubspec.yaml中设置的dart版本低于2.6.0则会出现警告提示

如:

environment:

sdk: “>=2.1.0 ❤️.0.0”

警告提示:

Extension methods weren’t supported until version 2.6.0

先来定义一个扩展函数

extension WidgetExt on Widget {

Container intoContainer({

//复制Container构造函数的所有参数(除了child字段)

Key key,

AlignmentGeometry alignment,

EdgeInsetsGeometry padding,

Color color,

Decoration decoration,

Decoration foregroundDecoration,

double width,

double height,

BoxConstraints constraints,

EdgeInsetsGeometry margin,

Matrix4 transform,

}) {

//调用Container的构造函数,并将当前widget对象作为child参数

return Container(

key: key,

alignment: alignment,

padding: padding,

color: color,

decoration: decoration,

foregroundDecoration: foregroundDecoration,

width: width,

height: height,

constraints: constraints,

margin: margin,

transform: transform,

child: this,

);

}

}

现在,所有widget对象都多了一个intoContainer(...)扩展函数,而且参数与Container构造方法一致,于是,我们就可以这样写了:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值