Flutter 布局容器边距

问题描述 投票:0回答:6

我的 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

layout dart containers margin flutter
6个回答
148
投票

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

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

29
投票

您可以尝试:到任意一条边的边距

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

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

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

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

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

9
投票
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),
  ),
),

2
投票

您可以尝试通过以下方式设置边距。

@override
Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        body: Container (
            // Even margin on all sides
            margin: EdgeInsets.all(10.0),
            // Symetric margin
            margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 5.0),
            // Different margin for all sides
            margin: EdgeInsets.fromLTRB(1.0, 2.0, 3.0, 4.0),
            // Margin only for left and right sides
            margin: const EdgeInsets.only(left: 10.0, right: 10.0),
            // Different margin for all sides
            margin: EdgeInsets.only(left: 5.0, top: 10.0, right: 15.0, bottom: 20.0),

            child: Child
            (
                ...
            ),
        ),
    );
}

0
投票

内边距和边距并排。

Container(
        padding: const EdgeInsets.fromLTRB(10, 10, 10, 10),
        margin: const EdgeInsets.fromLTRB(10, 10, 10, 10),
}

仅填充和边距。

Container(
        padding: const EdgeInsets.only(left: 10.0, right: 10.0),
        margin: const EdgeInsets.only(left: 10.0, right: 10.0),
}

所有边的内边距和边距都相同。

Container(
        padding: const EdgeInsets.all(10.0),
        margin: const EdgeInsets.all(10.0),
}

0
投票
 margin: const EdgeInsets.all(20.0),
© www.soinside.com 2019 - 2024. All rights reserved.