微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Flutter自适应文本字段匹配屏幕尺寸

如何解决Flutter自适应文本字段匹配屏幕尺寸

您好,我正在研究需要使用MediaQuery来响应所有屏幕尺寸的TextField进行响应的问题。我尝试了两种都不适合平板电脑的方式,那就是firstOne

Container(
                    height: 100.0,width: 300.0,child: TextField(
                      cursorColor: Colors.black,style: TextStyle(color: Colors.pinkAccent),controller: itemNameController,keyboardType: TextInputType.text,decoration: new Inputdecoration(
                        border: OutlineInputBorder(),labelText: 'Hello input here',isDense: true,contentPadding: EdgeInsets.only(
                            left: 5,bottom: 11,top: 11,right: 5),),

第二种方式是

                           TextField(
                          cursorColor: Colors.black,style: TextStyle(color: Colors.pinkAccent,height: 
                          MediaQuery.of(context).size.height/50),decoration: new Inputdecoration(
                            border: OutlineInputBorder(),contentPadding: EdgeInsets.only(
                                left: 5,
他们两个都没有反映在平板电脑上。谢谢

解决方法

您是否尝试过将MediaQuery用作包含TextField的容器的高度和宽度?

第一种方式,高度和宽度是固定的,因此TextField的大小不会改变。

以第二种方式,我相信“样式”用于更改TextField中的文本样式,而不是TextField。相反,如果要更改TextField的外观,请使用“装饰”。

,

我写了一个自适应类,将其调整为屏幕大小。我在小部件类中实现了该类,并根据屏幕尺寸给出了一个int值。这样,它会根据每部手机的屏幕大小调整大小。

class SizeConfig{
    
  double heightSize(BuildContext context,double value){
    value /= 100;
    return MediaQuery.of(context).size.height * value;
  }

  double widthSize(BuildContext context,double value ){
    value /=100;
    return MediaQuery.of(context).size.width * value;
  }
}

您可以像这样使用它;

Container(
                height: sizedConfig().heightSize(context,2.0)
                width: sizedConfig().widthSize(context,1.5),child: TextField(
                  cursorColor: Colors.black,style: TextStyle(color: Colors.pinkAccent),controller: itemNameController,keyboardType: TextInputType.text,decoration: new InputDecoration(
                    border: OutlineInputBorder(),labelText: 'Hello input here',isDense: true,contentPadding: EdgeInsets.only(
                        left: 5,bottom: 11,top: 11,right: 5),),
,

尽可能避免使用SizeConfig(自定义类)和硬编码尺寸。 例如:MediaQuery.of(context).size.width - someValue

制作响应式UI的最佳方法是Sizer插件。

任何屏幕尺寸的设备(平板电脑)中的响应UI。 检查这个插件plugin️
https://pub.dev/packages/sizer

.sp - for font size
.h  - for widget height
.w  - for widget width

如果要设置自适应文本字段的大小,则值后仅使用.w表示宽度,.h表示高度。

示例:

Container(
            height: 4.0.h    // 4% of screen height
            width: 80.0.w,// 80% of screen width
            child: TextField(
              cursorColor: Colors.black,decoration: new InputDecoration(
                border: OutlineInputBorder(),contentPadding: EdgeInsets.only(
                    left: 5.0.w,bottom: 1.0.h,top: 1.0.h,right: 5.0.w),

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。