首页 > 解决方案 > 是否可以在 Flutter 中连续放置一列?

问题描述

我尝试将一列放在一行中。但它不起作用。

然后我尝试使用不同的子属性将行和列放在同一个安全区域。这没用。

该列应该位于行的中间。

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.teal,
        body: SafeArea(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                height: 100.0,
                width: 100.0,
                color: Colors.yellow,
                child: Text('Container 1'),
              ),
              Container(
                height: 100.0,
                width: 100.0,
                color: Colors.green,
                child: Text('Container 1'),
              ),
              Container(
                width: double.infinity,
              ),
            ],
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Container(
                height: 100.0,
                color: Colors.red,
                child: Text('Container 1'),
              ),
              Container(
                height: 100.0,
                color: Colors.blue,
                child: Text('Container 1'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

错误消息是“BoxConstraints 强制使用无限宽度”。

标签: flutter-layout

解决方案


尝试使用 flex 属性扩展小部件,您可以将列放在一行中:

Container(
    width: 300,
    height: 100,
    child: Row(
      children: <Widget>[
        Expanded(flex: 1,
        child: Container(
          color: Colors.red,
          width: double.infinity,
          height: double.infinity,
        ),
        ),
        Expanded(flex: 2,
          child: Column(
            children: <Widget>[
              Expanded(flex:1,
                child: Container(
                  color: Colors.yellow,
                  width: double.infinity,
                  height: double.infinity,
                ),
              ),
              Expanded(flex:1,
                child: Container(
                  color: Colors.blue,
                  width: double.infinity,
                  height: double.infinity,
                ),
              ),
            ],
          ),
        ),
        Expanded(flex: 1,
          child: Container(
            color: Colors.green,
            width: double.infinity,
            height: double.infinity,
          ),
        ),
      ],
    ),
  ),

推荐阅读