UnconstrainedBox使用实践 2023-08-28

2023-08-27  本文已影响0人  勇往直前888

简介

在做Wrap相关的开发时,出现了元素被拉大的情况。经过实践,发现使用UnconstrainedBox可以有效改善这种情况。代码很简单,就是用文字表示标签。

没有居中

一开始的代码没有居中,文字有点偏:

Wrap(
  spacing: 5.w,
  runSpacing: 5.w,
  children: _selectTagList.map((tag) {
    return Container(
      height: 16.h,
      padding: EdgeInsets.only(left: 7.h, right: 7.h),
      decoration: BoxDecoration(
        color: ColorUtil.hexToColor(tag['bgColor']),
        borderRadius: BorderRadius.circular(8.h),
      ),
      child: Text(
        tag['name'] ?? '',
        style: TextStyle(
          color: PandaStyle.white,
          fontSize: 11.sp,
          fontWeight: FontWeight.w400,
        ),
      ),
    );
  }).toList(),
)
企业微信截图_511fd59e-9d72-4e14-b168-803141f6e849.png

添加居中

遇到这种情况,第一个想到的肯定是外面套一个Center(),让文字居中; 只是跑出来的结果有点出人意料。

Wrap(
  spacing: 5.w,
  runSpacing: 5.w,
  children: _selectTagList.map((tag) {
    return Container(
      height: 16.h,
      padding: EdgeInsets.only(left: 7.h, right: 7.h),
      decoration: BoxDecoration(
        color: ColorUtil.hexToColor(tag['bgColor']),
        borderRadius: BorderRadius.circular(8.h),
      ),
      child: Center(
        child: Text(
          tag['name'] ?? '',
          style: TextStyle(
            color: PandaStyle.white,
            fontSize: 11.sp,
            fontWeight: FontWeight.w400,
          ),
        ),
      ),
    );
  }).toList(),
)
企业微信截图_784b82be-5465-4b65-a8c6-c2ba422d21bd.png

消除副作用

Center()外面再套一层UnconstrainedBox(),副作用被取消了,达到了预期的效果。

Wrap(
  spacing: 5.w,
  runSpacing: 5.w,
  children: _selectTagList.map((tag) {
    return Container(
      height: 16.h,
      padding: EdgeInsets.only(left: 7.h, right: 7.h),
      decoration: BoxDecoration(
        color: ColorUtil.hexToColor(tag['bgColor']),
        borderRadius: BorderRadius.circular(8.h),
      ),
      child: UnconstrainedBox(
        child: Center(
          child: Text(
            tag['name'] ?? '',
            style: TextStyle(
              color: PandaStyle.white,
              fontSize: 11.sp,
              fontWeight: FontWeight.w400,
            ),
          ),
        ),
      ),
    );
  }).toList(),
)
企业微信截图_3f102c36-d23d-4ea6-9c0a-ba3f0f78828a.png

AppBar的例子

 AppBar(
   title: Text(title),
   actions: <Widget>[
     SizedBox(
       width: 20, 
       height: 20,
       child: CircularProgressIndicator(
         strokeWidth: 3,
         valueColor: AlwaysStoppedAnimation(Colors.white70),
       ),
     )
   ],
)

在这里SizedBox不起作用,是因为AppBar中做了我们看不到的限制

image.png
AppBar(
  title: Text(title),
  actions: <Widget>[
    UnconstrainedBox(
      child: SizedBox(
        width: 20,
        height: 20,
        child: CircularProgressIndicator(
          strokeWidth: 3,
          valueColor: AlwaysStoppedAnimation(Colors.white70),
        ),
      ),
    )
  ],
)
image.png
上一篇下一篇

猜你喜欢

热点阅读