首页 > 解决方案 > 创建设备高度背景元素

问题描述

我对扑扑很陌生,所以请公平。我想创建以下内容。

布局

我似乎无法弄清楚如何创建这个在拉出键盘时不应调整大小的背景元素。

我有这个,我希望有人能帮我一把。

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    var insetHeight = MediaQuery.of(context).viewInsets.bottom;

    return Scaffold(
      resizeToAvoidBottomPadding: false,
      body: Stack(
        children: <Widget>[
          Stack(
            children: <Widget>[
              Positioned(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height + insetHeight,
                child: Container(
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage("assets/images/background.png"),
                        fit: BoxFit.cover,
                        alignment: Alignment.bottomCenter,
                      ),
                    )
                ),
              ),
            ],
          ),

          SizedBox(
            width: 370,
            child: SingleChildScrollView(
              physics: PageScrollPhysics(), // dont really need this
              child: Column(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.all(20.0),
                    child: Text("Login to",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            fontFamily: "Opensans",
                            fontSize: 30,
                            letterSpacing: .6,
                            color: Colors.black45,
                            fontWeight: FontWeight.normal
                        )
                    ),
                  ),
                  Card(
                    child: Padding(padding: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 0), child: LoginForm()),
                  )
                ],
              ),
            )
          )
        ],
      ),
    );
  }
}

我尝试使用,MediaQuery.of(context).viewInsets.bottom;但它总是返回 0。

我不知道如何解决这个问题。

标签: flutterdart

解决方案


对于背景,请尝试以下操作:

  1. Size _screensize在 中创建一个变量_MyHomePageState
  2. 覆盖initState_MyHomePageState执行以下操作:
@override
void initState() {
  super.initState();
   _screenSize ??= MediaQuery.of(context).size;`
}
  1. _screenSize如下使用它:width_heightPositioned
    Positioned(
      width: _screenSize.width,
      height: _screenSize.height,
     ),

像往常一样添加其他普通小部件。

背景总结:

step 1:为要使用的尺寸创建一个私人参考。

step 2: 仅当私有大小变量为 null 时更新私有大小变量,即仅在第一次初始化小部件状态时。

step 3:使用私有大小作为背景的高度和宽度。


推荐阅读