【问题标题】:How to dynamically change the margin of a widget when the width of a window/device changes in flutter?当窗口/设备的宽度在颤动中发生变化时,如何动态更改小部件的边距?
【发布时间】:2021-09-21 09:56:26
【问题描述】:

我想在浏览器窗口宽度增加时增加容器小部件的边距。我怎样才能做到这一点? 我尝试使用 MediaQuery 类和其他响应式 UI 包,但边距和填充量保持不变

【问题讨论】:

  • 你试过LayoutBuilder

标签: android flutter dart web responsive-design


【解决方案1】:

您可以使用MediaQuery 并随着浏览器宽度的增加按百分比设置边距。

final size = MediaQuery.of(context).size.width;

EdgeInsets.symmetric(horizontal: size * 0.20) // 20% of the browserSize = padding

【讨论】:

    【解决方案2】:

    试试LayoutBuilder

    import 'package:flutter/material.dart';
    
    class FlexibleMargin extends StatelessWidget {
      const FlexibleMargin({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.cyanAccent,
          body: LayoutBuilder(
            builder: (context, constraints) => Center(
              ///this yellowAccent is showing margin area
              child: Container(
                color: Colors.yellowAccent,
                child: Container(
                  color: Colors.pinkAccent,
    
                  ///margin 4x for better view
                  margin: EdgeInsets.all(
                    (constraints.maxWidth * .02) * 4,
                  ),
                  // padding: EdgeInsets.all(
                  //   (constraints.maxWidth * .02) * 2,
                  // ),
                  child: Container(
                    height: constraints.maxHeight * .6,
                    width: constraints.maxWidth * .6,
                    color: Colors.blueAccent,
                  ),
                ),
              ),
            ),
          ),
        );
      }
    }
    
    

    【讨论】:

    • 不完全是我想要实现的,但 LayoutBuilder 确实帮了很多忙。谢谢!
    • 我的声望不到 15 ?
    猜你喜欢
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 2023-04-10
    • 2020-04-01
    • 2014-05-14
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    相关资源
    最近更新 更多