LiZhuoyuan

Merge branch 'beta'

# Conflicts:
#	README_CN.md
#	README_PT.md
... ... @@ -6,6 +6,15 @@
* @Description: Update log
-->
# 3.0.0-beta.2
- readme update
# 3.0.0-beta.1
**BREAKING CHANGES**
- `BuildContext` is no more required while initializing. i.e. ScreenUtil.init(~~context~~)
- Initialize size of design draft using `designSize` instead of width & height.
- All the static methods are now member methods.
# 2.3.1
- add textStyle Example.
... ...
# flutter_screenutil
[![pub package](https://img.shields.io/pub/v/flutter_screenutil.svg)](https://pub.dev/packages/flutter_screenutil)
... ... @@ -29,9 +28,8 @@ dependencies:
flutter:
sdk: flutter
# add flutter_screenutil
flutter_screenutil: ^2.3.0
flutter_screenutil: ^3.0.0-beta.1
```
### Add the following imports to your Dart code:
```
import 'package:flutter_screenutil/flutter_screenutil.dart';
... ... @@ -41,26 +39,31 @@ import 'package:flutter_screenutil/flutter_screenutil.dart';
|Property|Type|Default Value|Description|
|:---|:---|:---|:---|
|width|double|1080px|The width of the device in the design draft, in px|
|height|double|1920px|The height of the device in the design draft, in px|
|designSize|Size|Size(1080, 1920)|The size of the device in the design draft, in px|
|allowFontScaling|bool|false|Sets whether the font size is scaled according to the system's "font size" assist option|
### Initialize and set the fit size and font size to scale according to the system's "font size" accessibility option
Please set the width and height of the design draft before use, the width and height of the design draft (unit px).
Be sure to set the page in the MaterialApp's home/initialRoute(ie the entry file, just set it once) to ensure that the fit size is set before each use:
Please set the size of the design draft before use, the width and height of the design draft (unit px).
```dart
```
void main() {
WidgetsFlutterBinding.ensureInitialized();
//Set the fit size (fill in the screen size of the device in the design) If the design is based on the size of the iPhone6 ​​(iPhone6 ​​750*1334)
ScreenUtil.init(designSize: Size(750, 1334), allowFontScaling: false);
runApp(MyApp());
}
//fill in the screen size of the device in the design
//default value : width : 1080px , height:1920px , allowFontScaling:false
ScreenUtil.init(context);
ScreenUtil.init();
//If the design is based on the size of the iPhone6 ​​(iPhone6 ​​750*1334)
ScreenUtil.init(context, width: 750, height: 1334);
ScreenUtil.init(designSize: Size(750, 1334));
//If you want to set the font size is scaled according to the system's "font size" assist option
ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: true);
ScreenUtil.init(designSize: Size(750, 1334), allowFontScaling: true);
```
... ... @@ -77,12 +80,12 @@ ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: true);
ScreenUtil().setSp(24, allowFontScalingSelf: true) (sdk>=2.6 : 24.ssp) //Adapter font(fonts will scale to respect Text Size accessibility settings)
ScreenUtil().setSp(24, allowFontScalingSelf: false) (sdk>=2.6 : 24.nsp) //Adapter font(fonts will not scale to respect Text Size accessibility settings)
ScreenUtil.pixelRatio //Device pixel density
ScreenUtil.screenWidth (sdk>=2.6 : 1.wp) //Device width
ScreenUtil.screenHeight (sdk>=2.6 : 1.hp) //Device height
ScreenUtil.bottomBarHeight //Bottom safe zone distance, suitable for buttons with full screen
ScreenUtil.statusBarHeight //Status bar height , Notch will be higher Unit px
ScreenUtil.textScaleFactor //System font scaling factor
ScreenUtil().pixelRatio //Device pixel density
ScreenUtil().screenWidth (sdk>=2.6 : 1.wp) //Device width
ScreenUtil().screenHeight (sdk>=2.6 : 1.hp) //Device height
ScreenUtil().bottomBarHeight //Bottom safe zone distance, suitable for buttons with full screen
ScreenUtil().statusBarHeight //Status bar height , Notch will be higher Unit px
ScreenUtil().textScaleFactor //System font scaling factor
ScreenUtil().scaleWidth //Ratio of actual width dp to design draft px
ScreenUtil().scaleHeight //Ratio of actual height dp to design draft px
... ... @@ -119,7 +122,7 @@ height:200.h
```
**Note**
Height is also adapted according to setWidth to ensure no deformation (when you want a square)
The height can also use setWidth to ensure that it is not deformed(when you want a square)
setHeight method is mainly adapted in height, you want to control the height and actuality of a screen on the UIUsed when the same is displayed.
... ... @@ -135,23 +138,28 @@ Container(
////If you want to display a square:
Container(
width: ScreenUtil().setWidth(300),
height: ScreenUtil().setWidth(300),
height: 300.w,
),
```
#### Adapter font:
``` dart
//Incoming font size,the unit is pixel, fonts will not scale to respect Text Size accessibility settings
//(AllowallowFontScaling when initializing ScreenUtil)
ScreenUtil().setSp(28)
ScreenUtil().setSp(28)
28.sp
//Incoming font size,the unit is pixel,fonts will scale to respect Text Size accessibility settings
//(If somewhere does not follow the global allowFontScaling setting)
//(If somewhere follow the global allowFontScaling setting)
ScreenUtil().setSp(24, allowFontScalingSelf: true)
28.ssp
//for example:
//(If somewhere does not follow the global allowFontScaling setting)
ScreenUtil().setSp(24, allowFontScalingSelf: false)
28.nsp
//for example:
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
... ... @@ -171,167 +179,11 @@ Column(
)
```
```dart
//import
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter_ScreenUtil',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
//Set the fit size (fill in the screen size of the device in the design) If the design is based on the size of the iPhone6 ​​(iPhone6 ​​750*1334)
ScreenUtil.init(width: 750, height: 1334, allowFontScaling: false);
return ExampleWidget(title: 'FlutterScreenUtil Demo');
}
}
class ExampleWidget extends StatefulWidget {
const ExampleWidget({Key key, this.title}) : super(key: key);
final String title;
@override
_ExampleWidgetState createState() => _ExampleWidgetState();
}
class _ExampleWidgetState extends State<ExampleWidget> {
@override
Widget build(BuildContext context) {
printScreenInformation();
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Row(
children: <Widget>[
Container(
padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
width: ScreenUtil().setWidth(375),
height: ScreenUtil().setHeight(200),
color: Colors.red,
child: Text(
'My width:${ScreenUtil().setWidth(375)}dp \n'
'My height:${ScreenUtil().setHeight(200)}dp',
style: TextStyle(
color: Colors.white, fontSize: ScreenUtil().setSp(24)),
),
),
Container(
padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
width: ScreenUtil().setWidth(375),
height: ScreenUtil().setHeight(200),
color: Colors.blue,
child: Text(
'My width:${ScreenUtil().setWidth(375)}dp \n'
'My height:${ScreenUtil().setHeight(200)}dp',
style: TextStyle(
color: Colors.white,
fontSize: ScreenUtil().setSp(24))),
),
],
),
Text('Device width:${ScreenUtil.screenWidth}dp'),
Text('Device height:${ScreenUtil.screenHeight}dp'),
Text('Device width:${ScreenUtil.screenWidthPx}px'),
Text('Device height:${ScreenUtil.screenHeightPx}px'),
Text('Device pixel density:${ScreenUtil.pixelRatio}'),
Text('Bottom safe zone distance:${ScreenUtil.bottomBarHeight}dp'),
Text('Status bar height:${ScreenUtil.statusBarHeight}dp'),
Text(
'Ratio of actual width dp to design draft px:${ScreenUtil().scaleWidth}',
textAlign: TextAlign.center,
),
Text(
'Ratio of actual height dp to design draft px:${ScreenUtil().scaleHeight}',
textAlign: TextAlign.center,
),
SizedBox(
height: ScreenUtil().setHeight(100),
),
Text('System font scaling factor:${ScreenUtil.textScaleFactor}'),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'My font size is 24px on the design draft and will not change with the system.',
style: TextStyle(
color: Colors.black,
fontSize: ScreenUtil().setSp(24),
)),
Text(
'My font size is 24px on the design draft and will change with the system.',
style: TextStyle(
color: Colors.black,
fontSize: ScreenUtil()
.setSp(24, allowFontScalingSelf: true))),
],
)
],
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.title),
onPressed: () {
ScreenUtil.init(width: 1500, height: 1334, allowFontScaling: false);
setState(() {});
},
),
);
}
void printScreenInformation() {
print('Device width dp:${ScreenUtil.screenWidth}'); //Device width
print('Device height dp:${ScreenUtil.screenHeight}'); //Device height
print(
'Device pixel density:${ScreenUtil.pixelRatio}'); //Device pixel density
print(
'Bottom safe zone distance dp:${ScreenUtil.bottomBarHeight}'); //Bottom safe zone distance,suitable for buttons with full screen
print(
'Status bar height dp:${ScreenUtil.statusBarHeight}dp'); //Status bar height , Notch will be higher Unit dp
print(
'Ratio of actual width dp to design draft px:${ScreenUtil().scaleWidth}');
print(
'Ratio of actual height dp to design draft px:${ScreenUtil().scaleHeight}');
print(
'The ratio of font and width to the size of the design:${ScreenUtil().scaleWidth * ScreenUtil.pixelRatio}');
print(
'The ratio of height width to the size of the design:${ScreenUtil().scaleHeight * ScreenUtil.pixelRatio}');
}
}
```
### example:
### Example:
[example demo](/example/lib/main.dart)
effect:
### Effect:
![effect](demo_en.png)
![tablet effect](demo_tablet_en.png)
... ...
# flutter_ScreenUtil
[![pub package](https://img.shields.io/pub/v/flutter_screenutil.svg)](https://pub.dartlang.org/packages/flutter_screenutil)
**flutter 屏幕适配方案,让你的UI在不同尺寸的屏幕上都能显示合理的布局!**
*注意*:此插件仍处于开发阶段,某些API可能尚未推出。
[README of English](https://github.com/OpenFlutter/flutter_ScreenUtil/blob/master/README.md)
... ... @@ -36,7 +35,6 @@ dependencies:
# 添加依赖
flutter_screenutil: ^2.3.0
```
### 在每个使用的地方导入包:
```
import 'package:flutter_screenutil/flutter_screenutil.dart';
... ... @@ -56,15 +54,21 @@ import 'package:flutter_screenutil/flutter_screenutil.dart';
```
//填入设计稿中设备的屏幕尺寸
void main() {
WidgetsFlutterBinding.ensureInitialized();
//设置适配尺寸 (填入设计稿中设备的屏幕尺寸) 此处假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334)
ScreenUtil.init(designSize: Size(750, 1334), allowFontScaling: false);
runApp(MyApp());
}
//默认 width : 1080px , height:1920px , allowFontScaling:false
ScreenUtil.init(context);
ScreenUtil.init();
//假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334)
ScreenUtil.init(context, width: 750, height: 1334);
ScreenUtil.init(designSize: Size(750, 1334));
//设置字体大小根据系统的“字体大小”辅助选项来进行缩放,默认为false
ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: true);
ScreenUtil.init(designSize: Size(750, 1334), allowFontScaling: true);
```
... ... @@ -176,10 +180,12 @@ Column(
```
```dart
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
void main() => runApp( MyApp());
void main() {
WidgetsFlutterBinding.ensureInitialized();
//设置适配尺寸 (填入设计稿中设备的屏幕尺寸) 此处假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334)
ScreenUtil.init(designSize: Size(750, 1334), allowFontScaling: false);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
... ... @@ -190,30 +196,11 @@ class MyApp extends StatelessWidget {
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
home: ExampleWidget(title: 'FlutterScreenUtil示例'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
//设置适配尺寸 (填入设计稿中设备的屏幕尺寸) 此处假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334)
ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);
return ExampleWidget(title: 'FlutterScreenUtil示例');
}
}
class ExampleWidget extends StatefulWidget {
const ExampleWidget({Key key, this.title}) : super(key: key);
... ... @@ -243,7 +230,7 @@ class _ExampleWidgetState extends State<ExampleWidget> {
height: ScreenUtil().setHeight(200),
color: Colors.red,
child: Text(
'我的宽度:${ScreenUtil().setWidth(375)}dp \n'
'我的宽度:${0.5.wp}dp \n'
'我的高度:${ScreenUtil().setHeight(200)}dp',
style: TextStyle(
color: Colors.white, fontSize: ScreenUtil().setSp(24)),
... ... @@ -251,25 +238,25 @@ class _ExampleWidgetState extends State<ExampleWidget> {
),
Container(
padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
width: ScreenUtil().setWidth(375),
height: ScreenUtil().setHeight(200),
width: 375.w,
height: 200.h,
color: Colors.blue,
child: Text(
'我的宽度:${ScreenUtil().setWidth(375)}dp \n'
'我的高度:${ScreenUtil().setHeight(200)}dp',
'我的宽度:${375.w}dp \n'
'我的高度:${200.h}dp',
style: TextStyle(
color: Colors.white,
fontSize: ScreenUtil().setSp(24))),
),
],
),
Text('设备宽度:${ScreenUtil.screenWidth}dp'),
Text('设备高度:${ScreenUtil.screenHeight}dp'),
Text('设备宽度:${ScreenUtil.screenWidthPx}px'),
Text('设备高度:${ScreenUtil.screenHeightPx}px'),
Text('设备的像素密度:${ScreenUtil.pixelRatio}'),
Text('底部安全区距离:${ScreenUtil.bottomBarHeight}dp'),
Text('状态栏高度:${ScreenUtil.statusBarHeight}dp'),
Text('设备宽度:${ScreenUtil().screenWidthPx}px'),
Text('设备高度:${ScreenUtil().screenHeightPx}px'),
Text('设备宽度:${ScreenUtil().screenWidth}dp'),
Text('设备高度:${ScreenUtil().screenHeight}dp'),
Text('设备的像素密度:${ScreenUtil().pixelRatio}'),
Text('底部安全区距离:${ScreenUtil().bottomBarHeight}dp'),
Text('状态栏高度:${ScreenUtil().statusBarHeight}dp'),
Text(
'实际宽度的dp与设计稿px的比例:${ScreenUtil().scaleWidth}',
textAlign: TextAlign.center,
... ... @@ -279,22 +266,20 @@ class _ExampleWidgetState extends State<ExampleWidget> {
textAlign: TextAlign.center,
),
SizedBox(
height: ScreenUtil().setHeight(100),
height: 100.h,
),
Text('系统的字体缩放比例:${ScreenUtil.textScaleFactor}'),
Text('系统的字体缩放比例:${ScreenUtil().textScaleFactor}'),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('我的文字大小在设计稿上是24px,不会随着系统的文字缩放比例变化',
style: TextStyle(
color: Colors.black,
fontSize: ScreenUtil().setSp(24),
)),
Text('我的文字大小在设计稿上是24px,会随着系统的文字缩放比例变化',
style: TextStyle(
color: Colors.black,
fontSize: ScreenUtil()
.setSp(24, allowFontScalingSelf: true))),
Text(
'我的文字大小在设计稿上是24px,不会随着系统的文字缩放比例变化',
style: ts.t2,
),
Text(
'我的文字大小在设计稿上是24px,会随着系统的文字缩放比例变化',
style: ts.t1,
),
],
)
],
... ... @@ -303,7 +288,10 @@ class _ExampleWidgetState extends State<ExampleWidget> {
floatingActionButton: FloatingActionButton(
child: Icon(Icons.title),
onPressed: () {
ScreenUtil.init(width: 1500, height: 1334, allowFontScaling: false);
ScreenUtil.init(
designSize: Size(1500, 1334),
allowFontScaling: false,
);
setState(() {});
},
),
... ... @@ -311,20 +299,29 @@ class _ExampleWidgetState extends State<ExampleWidget> {
}
void printScreenInformation() {
print('设备宽度:${ScreenUtil.screenWidth}'); //Device width
print('设备高度:${ScreenUtil.screenHeight}'); //Device height
print('设备的像素密度:${ScreenUtil.pixelRatio}'); //Device pixel density
print('设备宽度:${ScreenUtil().screenWidth}'); //Device width
print('设备高度:${ScreenUtil().screenHeight}'); //Device height
print('设备的像素密度:${ScreenUtil().pixelRatio}'); //Device pixel density
print(
'底部安全区距离:${ScreenUtil.bottomBarHeight}dp'); //Bottom safe zone distance,suitable for buttons with full screen
'底部安全区距离:${ScreenUtil().bottomBarHeight}dp',
); //Bottom safe zone distance,suitable for buttons with full screen
print(
'状态栏高度:${ScreenUtil.statusBarHeight}dp'); //状态栏高度 , 刘海屏会更高,单位dp
'状态栏高度:${ScreenUtil().statusBarHeight}dp',
); //Status bar height , Notch will be higher Unit px
print('实际宽度的dp与设计稿px的比例:${ScreenUtil().scaleWidth}');
print('实际高度的dp与设计稿px的比例:${ScreenUtil().scaleHeight}');
print(
'宽度和字体相对于设计稿放大的比例:${ScreenUtil().scaleWidth * ScreenUtil.pixelRatio}');
print('高度相对于设计稿放大的比例:${ScreenUtil().scaleHeight * ScreenUtil.pixelRatio}');
print('系统的字体缩放比例:${ScreenUtil.textScaleFactor}');
'宽度和字体相对于设计稿放大的比例:${ScreenUtil().scaleWidth * ScreenUtil().pixelRatio}',
);
print(
'高度相对于设计稿放大的比例:${ScreenUtil().scaleHeight * ScreenUtil().pixelRatio}',
);
print('系统的字体缩放比例:${ScreenUtil().textScaleFactor}');
print('屏幕宽度的0.5:${0.5.wp}');
print('屏幕高度的0.5:${0.5.hp}');
}
}
... ...
# flutter_screenutil
[![pub package](https://img.shields.io/pub/v/flutter_screenutil.svg)](https://pub.dartlang.org/packages/flutter_screenutil)
... ... @@ -50,17 +49,22 @@ Por favor, defina a largura e altura do protótipo de design antes de usar (em p
Certifique-se de definir as dimensões na paginal inicial do MaterialApp (ou seja, no arquivo de entrada, defina apenas uma vez) para garantir que o tamanho de ajuste seja o mesmo antes de cada uso:
```dart
//Preencha o tamanho da tela do dispositivo no protótipo de design
void main() {
WidgetsFlutterBinding.ensureInitialized();
//Set the fit size (fill in the screen size of the device in the design) If the design is based on the size of the iPhone6 ​​(iPhone6 ​​750*1334)
ScreenUtil.init(designSize: Size(750, 1334), allowFontScaling: false);
runApp(MyApp());
}
//Valor padrão: width : 1080px , height:1920px , allowFontScaling:false
ScreenUtil.init(context);
ScreenUtil.init();
//Se o design é baseado no iPhone6 ​​(iPhone6 ​​750*1334)
ScreenUtil.init(context, width: 750, height: 1334);
ScreenUtil.init(designSize: Size(750, 1334));
//Se você quer definir que o tamanho da fonte seja ajustado de acordo com a opção "tamanho da fonte" na acessibilidade do sistema
ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: true);
ScreenUtil.init(designSize: Size(750, 1334), allowFontScaling: true);
```
... ... @@ -145,4 +149,160 @@ Container(
ScreenUtil().setSp(28)
//Tamanho da fonte informado,em pixels,a fonte irá dimensionar respeitando a opção "Tamanho de Fonte" nas configurações de acessibilidade
//(Se em algum lugar não seguir a configuração global da propriedade allowFontScaling
//(Se em algum lugar não seguir a configuração global da propriedade allowFontScaling)
ScreenUtil().setSp(24, allowFontScalingSelf: true)
//Exemplo:
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Minha fonte tem 24px no protótipo de design e não irá mudar com o sistema.',
style: TextStyle(
color: Colors.black,
fontSize: ScreenUtil().setSp(24),
)),
Text(
'Minha fonte tem 24px no protótipo de design e poderá mudar com o sistema.',
style: TextStyle(
color: Colors.black,
fontSize: ScreenUtil()
.setSp(24, allowFontScalingSelf: true))),
],
)
```
#### Outras APIs relacionadas:
```dart
ScreenUtil.pixelRatio //Densidade de pixels do dispositivo
ScreenUtil.screenWidth //Largura da tela do dispositivo
ScreenUtil.screenHeight //Altura da tela do dispositivo
ScreenUtil.bottomBarHeight //Distância segura do rodapé, adequada para botões em tela cheia
ScreenUtil.statusBarHeight //Altura da status bar em pixels, Notch será maior
ScreenUtil.textScaleFactor //Fator de escala da fonte do sistema
ScreenUtil().scaleWidth //Razão entre a largura atual e a largura do protótipo de design em pixels
ScreenUtil().scaleHeight //Razão entre a altura atual e a altura do protótipo de design em pixels
```
```dart
//import
import 'package:flutter_screenutil/flutter_screenutil.dart';
...
@override
Widget build(BuildContext context) {
///Define o tamanho de ajuste (preenche o tamanho da tela do dispositivo no design). Se o design é baseado no tamanho do iPhone6 (iPhone6 ​​750*1334)
ScreenUtil.init(designSize: Size(750, 1334), allowFontScaling: false);
print('Largura do dispositivo:${ScreenUtil().screenWidth}'); //Largura do dispositivo
print('Altura do dispositivo:${ScreenUtil().screenHeight}'); //Altura do dispositivo
print(
'Densidade de pixels do dispositivo:${ScreenUtil().pixelRatio}'); //Densidade de pixels do dispositivo
print(
'Distância segura do rodapé:${ScreenUtil().bottomBarHeight}'); //Distância segura do rodapé, adequada para botões em tela cheia
print(
'Altura da status bar:${ScreenUtil().statusBarHeight}px'); //Altura da status bar em pixels, Notch será maior
print(
'Razão entre a largura atual e a largura do protótipo de design em pixels:${ScreenUtil().scaleWidth}');
print(
'Razão entre a altura atual e a altura do protótipo de design em pixels:${ScreenUtil().scaleHeight}');
print(
'Razão da fonte e largura para o tamanho do design:${ScreenUtil().scaleWidth * ScreenUtil.pixelRatio}');
print(
'Razão da fonte e altura para o tamanho do design:${ScreenUtil().scaleHeight * ScreenUtil.pixelRatio}');
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Row(
children: <Widget>[
Container(
padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
width: ScreenUtil().setWidth(375),
height: ScreenUtil().setHeight(200),
color: Colors.red,
child: Text(
'Minha largura:${ScreenUtil().setWidth(375)}dp',
style: TextStyle(
color: Colors.white,
fontSize: ScreenUtil().setSp(12)),
),
),
Container(
padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
width: ScreenUtil().setWidth(375),
height: ScreenUtil().setHeight(200),
color: Colors.blue,
child: Text('Minha largura:${ScreenUtil().setWidth(375)}dp',
style: TextStyle(
color: Colors.white,
fontSize: ScreenUtil().setSp(12))),
),
],
),
Text('Largura do dispositivo:${ScreenUtil().screenWidth}dp'),
Text('Altura do dispositivo:${ScreenUtil().screenHeight}dp'),
Text('Densidade de pixels do dispositivo:${ScreenUtil().pixelRatio}'),
Text('Distância segura do rodapé:${ScreenUtil().bottomBarHeight}dp'),
Text('Altura da status bar:${ScreenUtil().statusBarHeight}dp'),
Text(
'Razão entre a largura atual e a largura do protótipo de design em pixels:${ScreenUtil().scaleWidth}',
textAlign: TextAlign.center,
),
Text(
'Razão entre a altura atual e a altura do protótipo de design em pixels:${ScreenUtil().scaleHeight}',
textAlign: TextAlign.center,
),
Text(
'Razão da fonte e largura para o tamanho do design:${ScreenUtil().scaleWidth * ScreenUtil.pixelRatio}',
textAlign: TextAlign.center,
),
Text(
'Razão da fonte e altura para o tamanho do design:${ScreenUtil().scaleHeight * ScreenUtil.pixelRatio}',
textAlign: TextAlign.center,
),
SizedBox(
height: ScreenUtil().setHeight(100),
),
Text('Fator de escala da fonte do sistema:${ScreenUtil.textScaleFactor}'),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Minha fonte tem 24px no protótipo de design e não irá mudar com o sistema.',
style: TextStyle(
color: Colors.black,
fontSize: ScreenUtil().setSp(24),
)),
Text(
'Minha fonte tem 24px no protótipo de design e poderá mudar com o sistema.',
style: TextStyle(
color: Colors.black,
fontSize: ScreenUtil().setSp(24, allowFontScalingSelf: true),
)),
],
)
],
),
),
);
}
```
### Exemplo:
[Demonstração](/example/lib/main_zh.dart)
Efeito:
![效果](demo_en.png)
![tablet effect](demo_tablet_en.png)
... ...
# example
flutter_screenutil example
# Example
![手机效果](../demo_zh.png)
![phone effect](../demo_en.png)
![平板效果](../demo_tablet_zh.png)
![tablet effect](../demo_tablet_en.png)
## Getting Started
```dart
void main() {
WidgetsFlutterBinding.ensureInitialized();
//Set the fit size (fill in the screen size of the device in the design) If the design is based on the size of the iPhone6 ​​(iPhone6 ​​750*1334)
ScreenUtil.init(designSize: Size(750, 1334), allowFontScaling: false);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter_ScreenUtil',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: ExampleWidget(title: 'FlutterScreenUtil Demo'),
);
}
}
class ExampleWidget extends StatefulWidget {
const ExampleWidget({Key key, this.title}) : super(key: key);
final String title;
@override
_ExampleWidgetState createState() => _ExampleWidgetState();
}
class _ExampleWidgetState extends State<ExampleWidget> {
@override
Widget build(BuildContext context) {
printScreenInformation();
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Row(
children: <Widget>[
// Using Extensions
Container(
padding: EdgeInsets.all(10.w),
width: 0.5.wp,
height: 200.h,
color: Colors.red,
child: Text(
'My width:${0.5.wp}dp \n'
'My height:${200.h}dp',
style: TextStyle(
color: Colors.white,
fontSize: 24.sp,
),
),
),
// Without using Extensions
Container(
padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
width: ScreenUtil().screenWidth * 0.5,
height: ScreenUtil().setHeight(200),
color: Colors.blue,
child: Text(
'My width:${ScreenUtil().screenWidth * 0.5}dp \n'
'My height:${ScreenUtil().setHeight(200)}dp',
style: TextStyle(
color: Colors.white,
fontSize: ScreenUtil().setSp(24),
),
),
),
],
),
Text('Device width:${ScreenUtil().screenWidthPx}px'),
Text('Device height:${ScreenUtil().screenHeightPx}px'),
Text('Device width:${ScreenUtil().screenWidth}dp'),
Text('Device height:${ScreenUtil().screenHeight}dp'),
Text('Device pixel density:${ScreenUtil().pixelRatio}'),
Text('Bottom safe zone distance:${ScreenUtil().bottomBarHeight}dp'),
Text('Status bar height:${ScreenUtil().statusBarHeight}dp'),
Text(
'Ratio of actual width dp to design draft px:${ScreenUtil().scaleWidth}',
textAlign: TextAlign.center,
),
Text(
'Ratio of actual height dp to design draft px:${ScreenUtil().scaleHeight}',
textAlign: TextAlign.center,
),
SizedBox(
height: ScreenUtil().setHeight(100),
),
Text('System font scaling factor:${ScreenUtil().textScaleFactor}'),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'My font size is 24px on the design draft and will not change with the system.',
style: TextStyle(
color: Colors.black,
fontSize: 24.sp,
),
),
Text(
'My font size is 24px on the design draft and will change with the system.',
style: ts.t1,
),
],
)
],
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.title),
onPressed: () {
ScreenUtil.init(
designSize: Size(1500, 1334),
allowFontScaling: false,
);
setState(() {});
},
),
);
}
void printScreenInformation() {
print('Device width dp:${ScreenUtil().screenWidth}'); //Device width
print('Device height dp:${ScreenUtil().screenHeight}'); //Device height
print(
'Device pixel density:${ScreenUtil().pixelRatio}'); //Device pixel density
print(
'Bottom safe zone distance dp:${ScreenUtil().bottomBarHeight}'); //Bottom safe zone distance,suitable for buttons with full screen
print(
'Status bar height px:${ScreenUtil().statusBarHeight}dp'); //Status bar height , Notch will be higher Unit px
print(
'Ratio of actual width dp to design draft px:${ScreenUtil().scaleWidth}');
print(
'Ratio of actual height dp to design draft px:${ScreenUtil().scaleHeight}');
print(
'The ratio of font and width to the size of the design:${ScreenUtil().scaleWidth * ScreenUtil().pixelRatio}');
print(
'The ratio of height width to the size of the design:${ScreenUtil().scaleHeight * ScreenUtil().pixelRatio}');
print('System font scaling:${ScreenUtil().textScaleFactor}');
print('0.5 times the screen width:${0.5.wp}');
print('0.5 times the screen height:${0.5.hp}');
}
}
```
... ...
*.iml
*.class
.gradle
gradle-wrapper.jar
/.gradle
/captures/
/gradlew
/gradlew.bat
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures
GeneratedPluginRegistrant.java
... ...
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>android</name>
<comment>Project android created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>app</name>
<comment>Project app created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>
... ... @@ -22,11 +22,16 @@ if (flutterVersionName == null) {
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion 28
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
lintOptions {
disable 'InvalidPackage'
}
... ... @@ -38,7 +43,6 @@ android {
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
... ... @@ -55,7 +59,5 @@ flutter {
}
dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
... ...
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="li.zhuoyuan.example">
<!-- Flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
... ...
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="li.zhuoyuan.example">
<!-- The INTERNET permission is required for development. Specifically,
flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
... ... @@ -20,20 +13,35 @@
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- This keeps the window background of the activity showing
until Flutter renders its first frame. It can be removed if
there is no splash screen (such as the default splash screen
defined in @style/LaunchTheme). -->
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<!-- Displays an Android View that continues showing the launch screen
Drawable until Flutter paints its first frame, then this splash
screen fades out. A splash screen is useful to avoid any visual
gap between the end of Android's launch screen and the painting of
Flutter's first frame. -->
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="@drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
... ...
package li.zhuoyuan.example;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
}
}
package li.zhuoyuan.example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
... ...
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
Flutter draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">@android:color/white</item>
</style>
</resources>
... ...
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="li.zhuoyuan.example">
<!-- Flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
... ...
buildscript {
ext.kotlin_version = '1.3.50'
repositories {
google()
jcenter()
maven { url "http://download.flutter.io" }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.2'
classpath 'com.android.tools.build:gradle:3.5.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
... ... @@ -14,7 +15,6 @@ allprojects {
repositories {
google()
jcenter()
maven { url "http://download.flutter.io" }
}
}
... ...
org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true
\ No newline at end of file
android.enableJetifier=true
... ...
... ... @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip
... ...
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
include ':app'
def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
def localPropertiesFile = new File(rootProject.projectDir, "local.properties")
def properties = new Properties()
def plugins = new Properties()
def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
if (pluginsFile.exists()) {
pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
}
assert localPropertiesFile.exists()
localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
plugins.each { name, path ->
def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
include ":$name"
project(":$name").projectDir = pluginDirectory
}
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"
... ...
#!/bin/sh
# This is a generated file; do not edit or check into version control.
export "FLUTTER_ROOT=/Users/lizhuoyuan/Development/flutter"
export "FLUTTER_APPLICATION_PATH=/Users/lizhuoyuan/Development/Project/flutter_screenutil/example"
export "FLUTTER_TARGET=lib/main.dart"
export "FLUTTER_ROOT=D:\Develop\flutter"
export "FLUTTER_APPLICATION_PATH=D:\Develop\Project\flutter_screenutil\example"
export "FLUTTER_TARGET=lib\main.dart"
export "FLUTTER_BUILD_DIR=build"
export "SYMROOT=${SOURCE_ROOT}/../build/ios"
export "FLUTTER_FRAMEWORK_DIR=/Users/lizhuoyuan/Development/flutter/bin/cache/artifacts/engine/ios"
export "SYMROOT=${SOURCE_ROOT}/../build\ios"
export "OTHER_LDFLAGS=$(inherited) -framework Flutter"
export "FLUTTER_FRAMEWORK_DIR=D:\Develop\flutter\bin\cache\artifacts\engine\ios"
export "FLUTTER_BUILD_NAME=1.0.0"
export "FLUTTER_BUILD_NUMBER=1"
export "DART_OBFUSCATION=false"
export "TRACK_WIDGET_CREATION=false"
export "TREE_SHAKE_ICONS=false"
export "PACKAGE_CONFIG=.packages"
... ...
import 'dart:ui';
import 'package:example/text_style.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
void main() => runApp(MyApp());
import 'text_style.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
//Set the fit size (fill in the screen size of the device in the design) If the design is based on the size of the iPhone6 ​​(iPhone6 ​​750*1334)
ScreenUtil.init(designSize: Size(750, 1334), allowFontScaling: false);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
... ... @@ -15,20 +21,11 @@ class MyApp extends StatelessWidget {
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
home: ExampleWidget(title: 'FlutterScreenUtil Demo'),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
//Set the fit size (fill in the screen size of the device in the design) If the design is based on the size of the iPhone6 ​​(iPhone6 ​​750*1334)
ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);
return ExampleWidget(title: 'FlutterScreenUtil Demo');
}
}
class ExampleWidget extends StatefulWidget {
const ExampleWidget({Key key, this.title}) : super(key: key);
... ... @@ -41,7 +38,7 @@ class ExampleWidget extends StatefulWidget {
class _ExampleWidgetState extends State<ExampleWidget> {
@override
Widget build(BuildContext context) {
printScreenInformation();
// printScreenInformation();
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
... ... @@ -52,39 +49,45 @@ class _ExampleWidgetState extends State<ExampleWidget> {
children: <Widget>[
Row(
children: <Widget>[
// Using Extensions
Container(
padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
width: 375.w,
padding: EdgeInsets.all(10.w),
width: 0.5.wp,
height: 200.h,
color: Colors.red,
child: Text(
'My width:${375.w}dp \n'
'My width:${0.5.wp}dp \n'
'My height:${200.h}dp',
style: TextStyle(
color: Colors.white, fontSize: ScreenUtil().setSp(24)),
color: Colors.white,
fontSize: 24.sp,
),
),
),
// Without using Extensions
Container(
padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
width: ScreenUtil().setWidth(375),
width: ScreenUtil().screenWidth * 0.5,
height: ScreenUtil().setHeight(200),
color: Colors.blue,
child: Text(
'My width:${0.5.wp}dp \n'
'My height:${ScreenUtil().setHeight(200)}dp',
style: TextStyle(
color: Colors.white,
fontSize: ScreenUtil().setSp(24))),
'My width:${ScreenUtil().screenWidth * 0.5}dp \n'
'My height:${ScreenUtil().setHeight(200)}dp',
style: TextStyle(
color: Colors.white,
fontSize: ScreenUtil().setSp(24),
),
),
),
],
),
Text('Device width:${ScreenUtil.screenWidthPx}px'),
Text('Device height:${ScreenUtil.screenHeightPx}px'),
Text('Device width:${ScreenUtil.screenWidth}dp'),
Text('Device height:${ScreenUtil.screenHeight}dp'),
Text('Device pixel density:${ScreenUtil.pixelRatio}'),
Text('Bottom safe zone distance:${ScreenUtil.bottomBarHeight}dp'),
Text('Status bar height:${ScreenUtil.statusBarHeight}dp'),
Text('Device width:${ScreenUtil().screenWidthPx}px'),
Text('Device height:${ScreenUtil().screenHeightPx}px'),
Text('Device width:${ScreenUtil().screenWidth}dp'),
Text('Device height:${ScreenUtil().screenHeight}dp'),
Text('Device pixel density:${ScreenUtil().pixelRatio}'),
Text('Bottom safe zone distance:${ScreenUtil().bottomBarHeight}dp'),
Text('Status bar height:${ScreenUtil().statusBarHeight}dp'),
Text(
'Ratio of actual width dp to design draft px:${ScreenUtil().scaleWidth}',
textAlign: TextAlign.center,
... ... @@ -96,19 +99,21 @@ class _ExampleWidgetState extends State<ExampleWidget> {
SizedBox(
height: ScreenUtil().setHeight(100),
),
Text('System font scaling factor:${ScreenUtil.textScaleFactor}'),
Text('System font scaling factor:${ScreenUtil().textScaleFactor}'),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'My font size is 24px on the design draft and will not change with the system.',
style: TextStyle(
color: Colors.black,
fontSize: 24.sp,
)),
'My font size is 24px on the design draft and will not change with the system.',
style: TextStyle(
color: Colors.black,
fontSize: 24.sp,
),
),
Text(
'My font size is 24px on the design draft and will change with the system.',
style: ts.t1),
'My font size is 24px on the design draft and will change with the system.',
style: ts.t1,
),
],
)
],
... ... @@ -117,8 +122,10 @@ class _ExampleWidgetState extends State<ExampleWidget> {
floatingActionButton: FloatingActionButton(
child: Icon(Icons.title),
onPressed: () {
ScreenUtil.init(context,
width: 1500, height: 1334, allowFontScaling: false);
ScreenUtil.init(
designSize: Size(750, 1334),
allowFontScaling: false,
);
setState(() {});
},
),
... ... @@ -126,23 +133,23 @@ class _ExampleWidgetState extends State<ExampleWidget> {
}
void printScreenInformation() {
print('Device width dp:${ScreenUtil.screenWidth}'); //Device width
print('Device height dp:${ScreenUtil.screenHeight}'); //Device height
print('Device width dp:${ScreenUtil().screenWidth}'); //Device width
print('Device height dp:${ScreenUtil().screenHeight}'); //Device height
print(
'Device pixel density:${ScreenUtil.pixelRatio}'); //Device pixel density
'Device pixel density:${ScreenUtil().pixelRatio}'); //Device pixel density
print(
'Bottom safe zone distance dp:${ScreenUtil.bottomBarHeight}'); //Bottom safe zone distance,suitable for buttons with full screen
'Bottom safe zone distance dp:${ScreenUtil().bottomBarHeight}'); //Bottom safe zone distance,suitable for buttons with full screen
print(
'Status bar height px:${ScreenUtil.statusBarHeight}dp'); //Status bar height , Notch will be higher Unit px
'Status bar height px:${ScreenUtil().statusBarHeight}dp'); //Status bar height , Notch will be higher Unit px
print(
'Ratio of actual width dp to design draft px:${ScreenUtil().scaleWidth}');
print(
'Ratio of actual height dp to design draft px:${ScreenUtil().scaleHeight}');
print(
'The ratio of font and width to the size of the design:${ScreenUtil().scaleWidth * ScreenUtil.pixelRatio}');
'The ratio of font and width to the size of the design:${ScreenUtil().scaleWidth * ScreenUtil().pixelRatio}');
print(
'The ratio of height width to the size of the design:${ScreenUtil().scaleHeight * ScreenUtil.pixelRatio}');
print('System font scaling:${ScreenUtil.textScaleFactor}');
'The ratio of height width to the size of the design:${ScreenUtil().scaleHeight * ScreenUtil().pixelRatio}');
print('System font scaling:${ScreenUtil().textScaleFactor}');
print('0.5 times the screen width:${0.5.wp}');
print('0.5 times the screen height:${0.5.hp}');
}
... ...
import 'package:example/text_style.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
void main() => runApp(MyApp());
import 'text_style.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
//设置适配尺寸 (填入设计稿中设备的屏幕尺寸) 此处假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334)
ScreenUtil.init(designSize: Size(750, 1334), allowFontScaling: false);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
... ... @@ -13,31 +19,11 @@ class MyApp extends StatelessWidget {
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
home: ExampleWidget(title: 'FlutterScreenUtil示例'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
//设置适配尺寸 (填入设计稿中设备的屏幕尺寸) 此处假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334)
ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);
return ExampleWidget(title: 'FlutterScreenUtil示例');
}
}
class ExampleWidget extends StatefulWidget {
const ExampleWidget({Key key, this.title}) : super(key: key);
... ... @@ -87,13 +73,13 @@ class _ExampleWidgetState extends State<ExampleWidget> {
),
],
),
Text('设备宽度:${ScreenUtil.screenWidthPx}px'),
Text('设备高度:${ScreenUtil.screenHeightPx}px'),
Text('设备宽度:${ScreenUtil.screenWidth}dp'),
Text('设备高度:${ScreenUtil.screenHeight}dp'),
Text('设备的像素密度:${ScreenUtil.pixelRatio}'),
Text('底部安全区距离:${ScreenUtil.bottomBarHeight}dp'),
Text('状态栏高度:${ScreenUtil.statusBarHeight}dp'),
Text('设备宽度:${ScreenUtil().screenWidthPx}px'),
Text('设备高度:${ScreenUtil().screenHeightPx}px'),
Text('设备宽度:${ScreenUtil().screenWidth}dp'),
Text('设备高度:${ScreenUtil().screenHeight}dp'),
Text('设备的像素密度:${ScreenUtil().pixelRatio}'),
Text('底部安全区距离:${ScreenUtil().bottomBarHeight}dp'),
Text('状态栏高度:${ScreenUtil().statusBarHeight}dp'),
Text(
'实际宽度的dp与设计稿px的比例:${ScreenUtil().scaleWidth}',
textAlign: TextAlign.center,
... ... @@ -105,7 +91,7 @@ class _ExampleWidgetState extends State<ExampleWidget> {
SizedBox(
height: 100.h,
),
Text('系统的字体缩放比例:${ScreenUtil.textScaleFactor}'),
Text('系统的字体缩放比例:${ScreenUtil().textScaleFactor}'),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
... ... @@ -125,8 +111,10 @@ class _ExampleWidgetState extends State<ExampleWidget> {
floatingActionButton: FloatingActionButton(
child: Icon(Icons.title),
onPressed: () {
ScreenUtil.init(context,
width: 1500, height: 1334, allowFontScaling: false);
ScreenUtil.init(
designSize: Size(750, 1334),
allowFontScaling: false,
);
setState(() {});
},
),
... ... @@ -134,21 +122,26 @@ class _ExampleWidgetState extends State<ExampleWidget> {
}
void printScreenInformation() {
print('设备宽度:${ScreenUtil.screenWidth}'); //Device width
print('设备高度:${ScreenUtil.screenHeight}'); //Device height
print('设备的像素密度:${ScreenUtil.pixelRatio}'); //Device pixel density
print('设备宽度:${ScreenUtil().screenWidth}'); //Device width
print('设备高度:${ScreenUtil().screenHeight}'); //Device height
print('设备的像素密度:${ScreenUtil().pixelRatio}'); //Device pixel density
print(
'底部安全区距离:${ScreenUtil.bottomBarHeight}dp'); //Bottom safe zone distance,suitable for buttons with full screen
'底部安全区距离:${ScreenUtil().bottomBarHeight}dp',
); //Bottom safe zone distance,suitable for buttons with full screen
print(
'状态栏高度:${ScreenUtil.statusBarHeight}dp'); //Status bar height , Notch will be higher Unit px
'状态栏高度:${ScreenUtil().statusBarHeight}dp',
); //Status bar height , Notch will be higher Unit px
print('实际宽度的dp与设计稿px的比例:${ScreenUtil().scaleWidth}');
print('实际高度的dp与设计稿px的比例:${ScreenUtil().scaleHeight}');
print(
'宽度和字体相对于设计稿放大的比例:${ScreenUtil().scaleWidth * ScreenUtil.pixelRatio}');
print('高度相对于设计稿放大的比例:${ScreenUtil().scaleHeight * ScreenUtil.pixelRatio}');
print('系统的字体缩放比例:${ScreenUtil.textScaleFactor}');
'宽度和字体相对于设计稿放大的比例:${ScreenUtil().scaleWidth * ScreenUtil().pixelRatio}',
);
print(
'高度相对于设计稿放大的比例:${ScreenUtil().scaleHeight * ScreenUtil().pixelRatio}',
);
print('系统的字体缩放比例:${ScreenUtil().textScaleFactor}');
print('屏幕宽度的0.5:${0.5.wp}');
print('屏幕高度的0.5:${0.5.hp}');
... ...
... ... @@ -4,91 +4,96 @@
*/
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
class ScreenUtil {
static ScreenUtil _instance;
static const int defaultWidth = 1080;
static const int defaultHeight = 1920;
static const Size defaultSize = Size(1080, 1920);
/// UI设计中手机尺寸 , px
/// Size of the phone in UI Design , px
num uiWidthPx;
num uiHeightPx;
Size uiSize = defaultSize;
/// 控制字体是否要根据系统的“字体大小”辅助选项来进行缩放。默认值为false。
/// allowFontScaling Specifies whether fonts should scale to respect Text Size accessibility settings. The default is false.
bool allowFontScaling;
static double _screenWidth;
static double _screenHeight;
static double _pixelRatio;
static double _statusBarHeight;
static double _bottomBarHeight;
static double _textScaleFactor;
ScreenUtil._();
bool allowFontScaling = false;
double _pixelRatio;
double _screenWidth;
double _screenHeight;
double _statusBarHeight;
double _bottomBarHeight;
double _textScaleFactor;
ScreenUtil._() {
final window = SchedulerBinding.instance?.window;
assert(
window != null,
'\nYou need to explicitly call the `WidgetsFlutterBinding.ensureInitialized()`, before initializing ScreenUtil.',
);
_pixelRatio = window.devicePixelRatio;
_screenWidth = window.physicalSize.width / _pixelRatio;
_screenHeight = window.physicalSize.height / _pixelRatio;
_statusBarHeight = window.padding.top;
_bottomBarHeight = window.padding.bottom;
_textScaleFactor = window.textScaleFactor;
}
factory ScreenUtil() {
assert(
_instance != null,
'\nEnsure to initialize ScreenUtil before accessing it.',
);
return _instance;
}
static void init(BuildContext context,
{num width = defaultWidth,
num height = defaultHeight,
bool allowFontScaling = false}) {
if (_instance == null) {
_instance = ScreenUtil._();
}
_instance.uiWidthPx = width;
_instance.uiHeightPx = height;
_instance.allowFontScaling = allowFontScaling;
MediaQueryData mediaQuery = MediaQuery.of(context);
_pixelRatio = mediaQuery.devicePixelRatio;
_screenWidth = mediaQuery.size.width;
_screenHeight = mediaQuery.size.height;
_statusBarHeight = mediaQuery.padding.top;
_bottomBarHeight = mediaQuery.padding.bottom;
_textScaleFactor = mediaQuery.textScaleFactor;
static void init({
Size designSize = defaultSize,
bool allowFontScaling = false,
}) {
_instance ??= ScreenUtil._();
_instance
..uiSize = designSize
..allowFontScaling = allowFontScaling;
}
/// 每个逻辑像素的字体像素数,字体的缩放比例
/// The number of font pixels for each logical pixel.
static double get textScaleFactor => _textScaleFactor;
double get textScaleFactor => _textScaleFactor;
/// 设备的像素密度
/// The size of the media in logical pixels (e.g, the size of the screen).
static double get pixelRatio => _pixelRatio;
double get pixelRatio => _pixelRatio;
/// 当前设备宽度 dp
/// The horizontal extent of this size.
static double get screenWidth => _screenWidth;
double get screenWidth => _screenWidth;
///当前设备高度 dp
///The vertical extent of this size. dp
static double get screenHeight => _screenHeight;
double get screenHeight => _screenHeight;
/// 当前设备宽度 px
/// The vertical extent of this size. px
static double get screenWidthPx => _screenWidth * _pixelRatio;
double get screenWidthPx => _screenWidth * _pixelRatio;
/// 当前设备高度 px
/// The vertical extent of this size. px
static double get screenHeightPx => _screenHeight * _pixelRatio;
double get screenHeightPx => _screenHeight * _pixelRatio;
/// 状态栏高度 dp 刘海屏会更高
/// The offset from the top
static double get statusBarHeight => _statusBarHeight;
double get statusBarHeight => _statusBarHeight;
/// 底部安全区距离 dp
/// The offset from the bottom.
static double get bottomBarHeight => _bottomBarHeight;
double get bottomBarHeight => _bottomBarHeight;
/// 实际的dp与UI设计px的比例
/// The ratio of the actual dp to the design draft px
double get scaleWidth => _screenWidth / uiWidthPx;
double get scaleWidth => _screenWidth / uiSize.width;
double get scaleHeight => _screenHeight / uiHeightPx;
double get scaleHeight => _screenHeight / uiSize.height;
double get scaleText => scaleWidth;
... ...
... ... @@ -18,9 +18,9 @@ extension SizeExtension on num {
///屏幕宽度的倍数
///Multiple of screen width
num get wp => ScreenUtil.screenWidth * this;
num get wp => ScreenUtil().screenWidth * this;
///屏幕高度的倍数
///Multiple of screen height
num get hp => ScreenUtil.screenHeight * this;
num get hp => ScreenUtil().screenHeight * this;
}
... ...
name: flutter_screenutil
description: A flutter plugin for adapting screen and font size.Guaranteed to look good on different models
version: 2.3.1
homepage: https://github.com/OpenFlutter/flutter_screenutil
version: 3.0.0-beta.2
homepage: https://github.com/OpenFlutter/flutter_screenutil/tree/beta
environment:
sdk: ">=2.6.0 <3.0.0"
flutter: ">=1.19.0-4.3.pre"
dependencies:
flutter:
... ... @@ -13,38 +14,3 @@ dependencies:
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# To add assets to your package, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
#
# For details regarding assets in packages, see
# https://flutter.io/assets-and-images/#from-packages
#
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.io/assets-and-images/#resolution-aware.
# To add custom fonts to your package, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts in packages, see
# https://flutter.io/custom-fonts/#from-packages
... ...