Flutter:ListView.builder 忽略 Container 子项的 BoxContrainst。始终应用完整的父级宽度

Mak*_*ros 4 flutter

在聊天应用程序中构建聊天气泡。我无法控制 ListView.builder 的 Container 子项的宽度。子容器始终采用 ListView.builders 父容器的完整宽度:
扩展 -> 容器宽度。

我想要实现的目标:消息气泡宽度尽可能小,同时仍包含消息文本,但不大于屏幕宽度的 75%。

对于这个简化的示例,忽略文本换行。

chatBubble 在哪里以及为什么会获得这个全屏宽度?

超级简化的小部件布局示例:

@override
Widget build(BuildContext context) {
  return Container(
    height: safeHeight,
    child: Column(
      children: <Widget>[
        Expanded(
          child: ListView.builder(
            itemCount: messages.length,
            itemBuilder: (ctx, i) => chatBubble(messages[i]),
          )
        ),
        Container(
          height: 50,
          child: TextField(/* stuff */),
        )
      ]
    )
  );
}

chatBubble(Message msg) {
  return Padding(
    padding: EdgeInsets.all(8.0),
    child: Container(
      color: Colors.lightBlue,
      child: Text(msg.text),
      constraints: BoxConstraints(
        maxWidth: screenWidth * 0.75,
      ),
    )
  )
}
Run Code Online (Sandbox Code Playgroud)

结果: 在此输入图像描述

Lui*_*lla 8

默认情况下, a 内的所有小部件ListView都会展开,但您可以使用其他小部件来保持内容的包裹。如果您有更多数据,chatBubble您可以使用一个Column或一个Wrap小部件,如下所示:

  chatBubble(Message msg) {
    return Wrap(
      children: [
       Padding(
        ...
        ),
       ],
    );
  }
Run Code Online (Sandbox Code Playgroud)

但是,如果您只想在该部分中提供一个子项,您可以使用Align Widget,它允许您使用alignment property来决定如何对齐子项。在这种情况下,请尝试以下操作:

 chatBubble(Message msg) {
    return Align(
      alignment: Alignment.centerRight,
      child: Padding(
        padding: EdgeInsets.all(8.0),
        child: ...
      ),
    );
  }
Run Code Online (Sandbox Code Playgroud)