如何根据条件将小部件向右或向左对齐

时间:2020-08-19 16:08:30

标签: flutter flutter-layout

我正在构建一个聊天窗口小部件,希望漫游器响应在左侧,用户响应在右侧。

但是,尽管我正确地识别了用户类型,但这两个响应都是从左开始的

如何修改代码,使BOT消息位于左侧,用户消息位于右侧

List<Widget> botMessage(context) {
    return <Widget>[
      Padding(
        padding: const EdgeInsets.only(left: 10.0, top: 10.0, bottom: 10.0),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            CircleAvatar(
              backgroundImage: AssetImage('assets/images/rce_icon.jpg'),
              radius: 10.0,
            ),
            SizedBox(
              width: 8.0,
            ),
            Container(
              constraints: BoxConstraints(
                maxWidth: MediaQuery.of(context).size.width * 0.7,
              ),
              padding:
                  const EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0),
              child: Padding(
                padding: const EdgeInsets.only(left: 10.0, right: 10.0),
                child: Text(
                  replies,
                ),
              ),
            )
          ],
        ),
      ),
    ];
  }
//should be align right
  List<Widget> userMessage(context) {
    return <Widget>[
      Padding(
        padding: const EdgeInsets.only(top: 10, bottom: 10.0, right: 25.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Container(
              constraints: BoxConstraints(
                maxWidth: MediaQuery.of(context).size.width * 0.7,
              ),
              padding:
                  const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0),
              child: Text(
                replies,
              ),
            )
          ],
        ),
      )
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 10.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: this.type ? botMessage(context) : userMessage(context),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

mainAxisAlignment小部件Row内添加mainAxisAlignment用于对齐

   Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment:
          this.type ? MainAxisAlignment.start : MainAxisAlignment.end,
      children: this.type ? botMessage(context) : userMessage(context),
    ),