likes
comments
collection
share

flutter:styled_widget

作者站长头像
站长
· 阅读数 4

简介

做过flutter开发都知道,当你写UI的时候避免不了widget的嵌套,一层一层又一层,当代码写多的了时候,看起来就非常的麻烦,后来我发现了styled_widget这个三方,可以通过链式变成的方式改变一层一层的嵌套,使用了一段时间代码清爽了很多

该三方主要是利用了dart2.7.0后引入的扩展方法,改变widget的树状编码为链式编码的

pub: pub.dev/packages/st… github: github.com/ReinBentdal…

例子

让我们先来看一个例子,一个简单的小正方形,外层是一个带阴影圆角的正方形, 内层分为两个圆形,中间带个Icon ,先来看看树状编码,再看一下使用styled_widget后的链式编码

树状编码

DecoratedBox(
  decoration: BoxDecoration(
    color: Color(0xffEBECF1),
  ),
  child: Align(
    alignment: Alignment.center,
    child: Card(
      elevation: 10,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20),
      ),
      child: Padding(
        padding: EdgeInsets.all(20),
        child: DecoratedBox(
          decoration: BoxDecoration(
            color: Color(0xffE8F2F7),
            shape: BoxShape.circle,
          ),
          child: Padding(
            padding: EdgeInsets.all(15),
            child: DecoratedBox(
              decoration: BoxDecoration(
                color: Color(0xff7AC1E7),
                shape: BoxShape.circle,
              ),
              child: Padding(
                padding: EdgeInsets.all(10),
                child: Icon(
                  OMIcons.home,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ),
    ),
  ),
);

链式编码

Icon(OMIcons.home, color: Colors.white)
  .padding(all: 10)
  .decorated(color: Color(0xff7AC1E7), shape: BoxShape.circle)
  .padding(all: 15)
  .decorated(color: Color(0xffE8F2F7), shape: BoxShape.circle)
  .padding(all: 20)
  .card(
    elevation: 10,
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(20),
    ),
  )
  .alignment(Alignment.center)
  .backgroundColor(Color(0xffEBECF1));

对比是不是很明显,在没使用链式编码之前的代码39行,使用了链式编码后只有十四行了,而且再也不用去对括号了,代码一下清爽很多有木有

动画及方法列表

另外styled_widget还提供了一些简单的动画配合一些widget进行使用

YourWidget()
  .padding(
    all: onTapState ? 10 : 20,
    animate: true,
  )
  .animation(
    duration: Duration(milliseconds: 300),
    curve: Curves.easeOut,
  )

目前所有的方法都在github上,感兴趣的小伙伴可以提前看一下,之后我也会把所有的方法的介绍一遍

结语

希望大家把一些好的三方分享出来,打在评论区,共同学习,共同进步

作为Flutter届的一个小学生,希望大家多多指教,有问题的地方一起讨论