Flutter响应文本字段匹配屏幕大小



你好,我正在处理flutter,需要使用匹配所有屏幕大小的MediaQuery使我的TextField响应。我尝试了两种方法,两种方法都不适用于平板电脑,这是第一种

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),
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),
),
),

两人都没有在平板电脑上反映。感谢

我编写了一个响应类,它可以根据屏幕大小调整大小。我在小部件类中实现了这个类,并根据屏幕大小给出一个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),
),
),
),

您是否尝试将MediaQuery设置为包含TextField的容器的高度和宽度?

第一种方法是,高度和宽度是固定的,所以TextField的大小不会改变。

在你的第二种方式中,我相信"风格";用于更改TextField中文本的样式,而不是TextField。相反,使用";装饰;如果要更改TextField的外观。

尽可能避免SizeConfig(自定义类(和硬编码维度。示例:MediaQuery.of(context).size.width - someValue

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

任何屏幕大小的设备以及平板电脑中的响应式UI。检查一下这个插件⬇️
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,
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.0.w, bottom: 1.0.h, top: 1.0.h, right: 5.0.w),
),
),
),

最新更新