首页 > 解决方案 > 如何设置图片/按钮/文本的位置以响应其他设备?

问题描述

我尝试通过定义数字来设置图片/按钮/文本的位置,但是当我的代码运行到其他设备时,我的 UI 与在我的设备上运行的不同。这是在我的设备和其他设备上显示结果的图片。

我的设备

其他设备

因此,我尝试使用此代码来使我的代码具有响应性。

 Container(
   child: Positioned(
      left: MediaQuery.of(context).size.width*0.4,
      top:  MediaQuery.of(context).size.height*0.28,
      width: 100,
      height: 100,
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
             image: AssetImage("assets/images/LG5.png"))),
  ))),

为了设置按钮的位置和登录 TextFiled 我使用这个代码

Container(
  margin: const EdgeInsets.only(left: 80.0, right: 80.0, top: 300),
child: Column(
  children: <Widget>[
    TextField(
              obscureText: true,
              decoration: InputDecoration(
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(20)),
                  borderSide:
                      BorderSide(width: 3, color: Colors.indigo[700]),
                ),
                labelText: 'Password',
              ),
            ),
    TextField(
              decoration: InputDecoration(
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(20)),
                  borderSide:
                      BorderSide(width: 3, color: Colors.indigo[700]),
                ),
                labelText: 'Username',
              ),
            ),
Container(
  width: 300,
  margin: const EdgeInsets.only(top: 40),
    child: RaisedButton(
      child: Text('Login',
                style: TextStyle(color: Colors.white, fontSize: 20)),
                color: Colors.indigo[700],
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20)),
                padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                onPressed: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => HomeScreen()));
                }),
  )

对于上面的代码,我使用此代码来设置 TextFiled 的位置

margin: const EdgeInsets.only(left: 80.0, right: 80.0, top: 300)

登录按钮是

margin: const EdgeInsets.only(top: 40)

如您所见,我定义了该位置的编号,并尝试使用此代码并分配给“EdgeInsets.only”的左、右、顶部,但它不起作用。

MediaQuery.of(context).size.width 
MediaQuery.of(context).size.height

那么,我怎样才能用“EdgeInsets.only”定义左、右、顶的值,而不需要固定数字,它会响应其他设备?

或者,您可以建议我采用另一种比这种方式更合适的方式,因为我不确定我的方式是否正确。我刚学Flutter。

谢谢你。

标签: flutterdartflutter-layout

解决方案


不要使用 20、30 等绝对值,而是尝试使用 %。这样你的用户界面就会响应


推荐阅读