【问题标题】:Flutter Layout Container MarginFlutter 布局容器边距
【发布时间】:2018-08-28 10:12:33
【问题描述】:

我的 Flutter 布局有问题。

我有一个简单的容器,其左右边距为 20.0 在这个容器里面我有另一个容器。

但是这个容器不适合仅在左侧的父容器。 我不知道为什么会这样。

这是我的代码:

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      backgroundColor: Colors.white,
      body: new Container(
        margin: new EdgeInsets.symmetric(horizontal: 20.0),
        child: new Container(

        )
      ),
    );
  }

Screenshot of the Problem

【问题讨论】:

  • 你确定吗?我们可以清楚地看到两边的两条竖线。
  • 是的父容器是对的,但是子容器不适合父容器(标记为蓝色区域)
  • 已解决。在 Inspector 我的错中选择了错误的小部件
  • 如果您想知道子 Widget 如何适合父 Widget,只需将子 Widget 包裹在容器中并为容器赋予颜色

标签: layout dart containers margin flutter


【解决方案1】:

你可以使用左值和右值:)

@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Colors.white,
    body: Container(
      margin: const EdgeInsets.only(left: 20.0, right: 20.0),
      child: Container(),
    ),
  );
}

【讨论】:

  • 也可以使用“margin: EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 0.0)”。
  • 你为什么写const
  • @Cold_Class const 是一个关键字,表示构造函数是 const 构造函数,即它只能获取编译时值,而不是像某些变量一样在运行时计算的值。
  • @KushagraSaxena 这样做有什么好处——比如性能提升?因为我认为将多个元素的边距值存储在一个变量中可能会非常有用。
  • @Cold_Class 不,它与性能无关。它只是飞镖说要遵循的约定。 dart.dev/guides/language/effective-dart/…
【解决方案2】:

你可以试试:到任意一条边的边缘

new Container(
    margin: const EdgeInsets.only(left: 20.0, right: 20.0),
    child: new Container()
)

您可以尝试:到任何所有边缘的边缘

new Container(
    margin: const EdgeInsets.all(20.0),
    child: new Container()
)

如果您需要当前的系统填充或视图 insets 的上下文 小部件,考虑使用 [MediaQuery.of] 来获取这些值,而不是 使用 [dart:ui.window] 中的值,以便您收到更改通知。

new Container(
    margin: EdgeInsets.fromWindowPadding(padding, devicePixelRatio),
    child: new Container()
)

【讨论】:

    【解决方案3】:
    Container(
      margin: EdgeInsets.all(10) ,
      alignment: Alignment.bottomCenter,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: <Color>[
            Colors.black.withAlpha(0),
            Colors.black12,
            Colors.black45
          ],
        ),
      ),
      child: Text(
        "Foreground Text",
        style: TextStyle(color: Colors.white, fontSize: 20.0),
      ),
    ),
    

    【讨论】:

    • 你能补充一些细节来解释你的代码是如何回答这个问题的吗?
    猜你喜欢
    • 2017-05-10
    • 2019-01-28
    • 1970-01-01
    • 2013-09-19
    • 2013-11-23
    • 2013-08-28
    • 2019-01-01
    • 1970-01-01
    • 2012-10-12
    相关资源
    最近更新 更多