在 Flutter 中限制容器的最大宽度 [英] Limit max width of Container in Flutter

查看:90
本文介绍了在 Flutter 中限制容器的最大宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  Widget build(context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 300,
          padding: EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: color ?? Colors.blue,
            borderRadius: BorderRadius.circular(10)
          ),
          child: msg
        )
      ],  
    );
  }

这是我的小部件的构建方法,它根据我作为 msg 参数传递的内容呈现此 UI

This is build method of my widget and It renders this UI depending on what I pass as msg paramter

  1. 正在加载文本
  2. 一些很长的文字

现在我面临的问题是,我无法在不设置宽度的情况下将文本包裹在此容器/蓝色框内,但是如果我设置了容器/蓝色框的宽度,那么无论多短,它都会保持那么宽正文是.

Now the issue I am facing is that I am not able to wrap the text inside this container/blue box without setting it's width but If I set width of container/blue box then it will always stay that wide no matter how short the text is.

现在有没有办法设置容器/蓝框的 maxWidth(比如 500)?这样蓝色框将变得与加载"等小文本所需的宽度一样宽,而对于长文本,它将扩展到 500 个单位的宽度,然后将文本换行?

Now is there a way to set maxWidth (like let's say 500) of container/blue box? So that the blue box will become as wide as required for small text like "Loading" and for long text it will expand till it reaches width of 500 units and then will wrap the text ?

长文本所需的输出:

对于像加载这样的小文本,我不希望 UI 有任何变化,但对于长文本,我希望它看起来像这样.

For small text like loading I dont want any change in UI but for long text I want it to look like this.

推荐答案

您可以使用首选的 maxWidth 向 Container Widget 添加约束,如下所示:

You can add a constraint to the Container Widget with the preferred maxWidth like this:

Widget build(context) {
return Row(
  mainAxisSize: MainAxisSize.min,
  children: [
    Container(
      constraints: BoxConstraints(minWidth: 100, maxWidth: 200),
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: color ?? Colors.blue,
        borderRadius: BorderRadius.circular(10)
      ),
      child: msg
    )
  ],  
);
}

我希望这会有所帮助!

这篇关于在 Flutter 中限制容器的最大宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆