【问题标题】:Flutter: how to create widget positioned relative to the screen?Flutter:如何创建相对于屏幕定位的小部件?
【发布时间】:2020-09-02 17:12:17
【问题描述】:

基本上我需要创建某种可以在任何页面上创建的 Snackbar 小部件。所以我需要让它相对于屏幕定位。唯一的想法是创建将包装所有其他页面的主 Stack 小部件。你还有其他建议吗?我发现pretty similar question 没有任何有趣的答案

【问题讨论】:

    标签: flutter layout positioning


    【解决方案1】:

    通过使用Mediaquery获取屏幕尺寸。

    例如我们可以这样设置屏幕宽度:

    MediaQueryData screenSize = MediaQuery.of(context).size.width;
    

    假设我希望我的容器大小占据屏幕大小的一半

    一种方法是这样的:

    Container(
    height: MediaQuery.of(context).size.height/2,
    width: MediaQuery.of(context).size.width/2,
    child: Text('This container is half this device screen's size');
    );
    

    您在这里要做的是使用Positioned 小部件

    让我们以最后一个例子为例,在每一边留下四分之一的屏幕:

        Container(
        height: MediaQuery.of(context).size.height/2,
        width: MediaQuery.of(context).size.width/2,
        child: child: Stack(
        children: <Widget>[
          Positioned(
            left: MediaQuery.of(context).size.width/4,
            top: MediaQuery.of(context).size.height/4,
            right: MediaQuery.of(context).size.width/4,
            bottom: MediaQuery.of(context).size.height/4,
            child: Text('This container is half this device screen's size'),
          ),
        ],
      ),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 2021-05-15
      • 2020-08-19
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多