【问题标题】:Flutter: how to fit widget with aspect ratio inside its parent?Flutter:如何在其父级内适应具有纵横比的小部件?
【发布时间】:2021-08-10 07:02:03
【问题描述】:

我想在一个容器中有两个小部件中心。

小部件 A 具有 1:1 的纵横比并适合容器。

Widget B 是一个 Text,它的高度适合内容,宽度填充父级。

例如:

纵向模式

横向模式

这是我尝试过的代码:

  Widget build(BuildContext context) {

    return Scaffold(
        appBar: AppBar(
          // Here we take the value from the MyHomePage object that was created by
          // the App.build method, and use it to set our appbar title.
          title: Text(widget.title),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(
                flex: 1,
                child: Container(
                  color: Colors.deepPurple,
                  child: AspectRatio(
                    aspectRatio: 1 / 1,
                    child: Container(color: Colors.yellow),
                  ),
                )),
            Container(
                color: Colors.green,
                child: Center(child: Text("TEST", textAlign: TextAlign.center)))
          ],
        ));
  }

但是结果是这样的:

纵向模式

横向模式

小部件 A 在纵向模式下填充所有空间,而不是适合内部。

如何让Widget A适合容器?

【问题讨论】:

  • “如何在其父级内设置具有纵横比的小部件?” - 请参阅FittedBox
  • @pskink 单个 FittedBox 是如何完成所有中心、拟合和纵横比的工作的?
  • 你想知道所有的细节吗?如果是,请检查RenderFittedBox source 文件

标签: flutter flutter-layout hybrid-mobile-app aspect-ratio


【解决方案1】:

我做了一些改变。你可以试试这个。也许这不是正确有效的方法。不过你可以试试。

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    //Calculate width and height as your wish
    double width = size.width < size.height ? size.width : size.height * .5;
    double height = width * 1.1;
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              color: Colors.deepPurple,
              child:
                  Container(width: width, height: height, color: Colors.yellow),
            ),
            Container(
                color: Colors.green,
                child: Center(child: Text("TEST", textAlign: TextAlign.center)))
          ],
        ));
  }

【讨论】:

    猜你喜欢
    • 2013-10-31
    • 2018-10-21
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 2017-11-16
    • 2010-10-01
    • 1970-01-01
    • 2021-03-13
    相关资源
    最近更新 更多