Flutter Layout行/列-共享宽度,扩展高度

时间:2018-07-13 13:23:06

标签: flutter flutter-layout

Flutter的版式仍然有些麻烦。
现在,我要以象限布局在3个小部件之间共享可用空间。 宽度是平均分配的(通过连续2个Expanded小部件可以正常工作),但是现在我还希望高度自动调整,因此widget3.height == widget1.height + widget2.heightlayout 如果widget3的内容较大,我希望widget1widget2调整其高度,反之亦然。

在Flutter中甚至有可能吗?

2 个答案:

答案 0 :(得分:40)

看看IntrinsicHeight;包裹根行应提供您想要的效果:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(title: Text('Rows & Columns')),
        body: RowsAndColumns(),
      ),
    );
  }
}

class RowsAndColumns extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 100.0),
      child: IntrinsicHeight(
        child: Row(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
          Expanded(
            child: Column(children: [
              Container(height: 120.0, color: Colors.yellow),
              Container(height: 100.0, color: Colors.cyan),
            ]),
          ),
          Expanded(child: Container(color: Colors.amber)),
        ]),
      ),
    );
  }
}

调整列中容器的高度会使右侧的容器调整大小以匹配:

screenshot

https://gist.github.com/mjohnsullivan/c5b661d7b3b4ca00599e8ef87ff6ac61

答案 1 :(得分:0)

我是新手。如果我在这里做错了,请纠正我。我认为也可以使用setState((){})而不使用IntrinsicHeight来实现。

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}`enter code here`

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    double h1 = 100;
    double h2 = 200;
    double h3;
    setState(() {
      h3 = h1 + h2;
    });
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.only(top: 100.0),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: Column(
                    children: [
                      Container(
                        color: Colors.green,
                        height: h1,
                      ),
                      Container(
                        color: Colors.orange,
                        height: h2,
                      )
                    ],
                  ),
                ),
                Expanded(
                  child: Container(
                    color: Colors.yellow,
                    height: h3,
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Find image here

代码也可以在这里找到:https://gist.github.com/Amrit0786/9d228017c2df6cf277fbbaa4a6b20e83