Flutter third-party flutter_screenutil (screen adaptation)

I have always felt that what I write is not about technology, but about feelings. Each tutorial is a trace of my journey along the way. Success based on professional skills is the most replicable. I hope that my path will help you avoid detours. I hope that I can help you wipe away the dust of knowledge. I hope that I can help you clarify the context of knowledge. I hope that in the future There are you and me at the top of technology.

Recommend a very well-written article: Flutter application framework construction (2) Screen adaptation

Install + Import

flutter_screenutil: ^5.9.0
import 'package:flutter_screenutil/flutter_screenutil.dart';

Examples

iPhone 12 mini

Initialization

Initialization – Set reference size 1

ScreenUtilInit

class MyApp extends StatelessWidget {<!-- -->
  const MyApp({<!-- -->super.key});

  @override
  Widget build(BuildContext context) {<!-- -->
    return ScreenUtilInit(
      designSize: const Size(750, 1334),//iphone6 750 1334 iphone 12 mini 1080 2340
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (_ , child) {<!-- -->
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'First Method',
          // You can use the library anywhere in the app even in theme
          theme: ThemeData(
            primarySwatch: Colors.blue,
            textTheme: Typography.englishLike2018.apply(fontSizeFactor: 1.sp),
          ),
          // home: child,
          initialRoute: Home.routeName,
          routes: {<!-- -->
            Home.routeName: (context) => Home(),
          },
        );
      },
      // child: Home(),
    );
  }

}

Initialization – Setting method 2

ScreenUtil.init

Can be set on each page

class MyApp extends StatelessWidget {<!-- -->
  @override
  Widget build(BuildContext context) {<!-- -->
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter_ScreenUtil',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(title: 'FlutterScreenUtil Demo'),
    );
  }
}

class HomePage extends StatefulWidget {<!-- -->
  const HomePage({<!-- -->Key key, this.title}) : super(key: key);

  final String title;

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {<!-- -->
  @override
  Widget build(BuildContext context) {<!-- -->
    //Set the size (fill in the screen size of the device in the design) if the design is based on a 360dp * 690dp screen
    ScreenUtil.init(context, designSize: const Size(360, 690));
    ...
  }
}

To use this method, you only need to initialize it before using flutter_screenutil. It is usually initialized when the root route is loaded, that is, the first page.

Note: ScreenUtil.init cannot be initialized in MyApp, and the following error will be reported: No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of(). This can happen because you have not added a WidgetsApp, CupertinoApp, or MaterialApp widget (those widgets introduce a MediaQuery), or it can happen if the context you use comes from a widget above those widgets. Because MaterialApp has not been loaded yet, you cannot use MediaQuery.of(context) to get the screen width and height.

Regarding the above two initialization methods, the author of flutter_screenutil recommends using the second method.

Use

double screenWidth = MediaQuery.of(context).size.width;
double screenHeight = MediaQuery.of(context).size.height;
print('System width: $screenWidth');//375.0
print('System height: $screenHeight');//812.0

double utilWidth = ScreenUtil().screenWidth;
double utilHeight = ScreenUtil().screenHeight;
print('ScreenUtil width: $utilWidth');//Device width 375.0
print('ScreenUtil height: $utilHeight');//Device height 812.0

double pixelRatio = ScreenUtil().pixelRatio  0.0;
print('pixelRatio $pixelRatio');//The pixel density of the device is 3.0

double bottomBarHeight = ScreenUtil().bottomBarHeight;
print('bottomBarHeight $bottomBarHeight');//The distance of the bottom safety zone, suitable for 34.0 with buttons under the full screen

double statusBarHeight = ScreenUtil().statusBarHeight;
print('statusBarHeight $statusBarHeight');//Status bar height Liu Haiping will be higher 50.0

double textScaleFactor = ScreenUtil().textScaleFactor;
print('textScaleFactor $textScaleFactor');//System font scaling ratio 1.0

double scaleWidth = ScreenUtil().scaleWidth;//The ratio of the actual width to the width of the design draft 0.5
print('scaleWidth $scaleWidth');
double scaleHeight = ScreenUtil().scaleHeight;//The ratio of actual height to design draft height 0.6
print('scaleHeight $scaleHeight');

Orientation orientation = ScreenUtil().orientation;// screen orientation .portrait
print('orientation $orientation');

Set the width of the screen’s Container to half the screen width

/// The width and height are 0.5 times the width, displaying a square
Container(
  width: 0.5.sw,
  height: 0.5.sw,
  color: Colors.green,
),

Set according to width

//Method 1:
ScreenUtil().setWidth(540) //Adapt the size according to the screen width

//Method 2:
540.w

Set according to height

//Method 1:
ScreenUtil().setHeight(200) //Adapt the size according to the screen height (usually it can be adapted according to the width)

//Method 2:
200.h

Adjust to the smaller of width or height

//Method 1:
ScreenUtil().radius(200) //Adjust according to the smaller of width or height

//Method 2:
200.r

Font size adaptation

ScreenUtil().setSp(24) //Font size adaptation

//method one:
Text("Hello", style: TextStyle(fontSize: ScreenUtil().setSp(24)),),

//Method 2:
Text("Hello", style: TextStyle(fontSize: 24.sp),),

In addition to the above four extended attributes, sm and sw, sh are also provided

sm: Take the smallest value between the value itself and the value of sp, such as 12.sm, take 12 and 12.sp are compared and the smallest value is taken.
sw: The abbreviation of screen width, that is, the screen width, is used to return a value in proportion to the screen width. For example, 0.2.sw returns 20% of the screen width, and 1.sw returns the entire screen width.
sh: The abbreviation of screen height, and screen height. Its function is similar to sw, returning the screen height value of the specified ratio. For example, 1.sh is the entire screen height

Note

If you use sp to set the font, the font will be scaled according to the width and height of the screen. If you need to set it so that the font size is the same for all screens, you can design it as follows:

Global settings:

MaterialApp(
  debugShowCheckedModeBanner: false,
  title: 'Flutter_ScreenUtil',
  theme: ThemeData(
    primarySwatch: Colors.blue,
  ),
  builder: (context, widget) {<!-- -->
    return MediaQuery(
      ///Set text size not to change with system settings
      data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
      child: widget,
    );
  },
  home: HomePage(title: 'FlutterScreenUtil Demo'),
),

Text is set individually:

Text("text", textScaleFactor: 1.0)

Other APIs

In addition to the adapted APIs, flutter_screenutil also provides many practical APIs, as follows:

ScreenUtil().pixelRatio: The pixel density of the device
ScreenUtil().screenWidth: screen width, equivalent to 1.sw
ScreenUtil().screenHeight: screen height, equivalent to 1.sh
ScreenUtil().bottomBarHeight: bottom navigation height, such as the height of the bottom button of the full screen
ScreenUtil().statusBarHeight: status bar height
ScreenUtil().textScaleFactor: System font scaling ratio
ScreenUtil().scaleWidth: The ratio of the actual width to the width of the design drawing
ScreenUtil().scaleHeight: The ratio of the actual height to the height of the design drawing
ScreenUtil().orientation: Screen orientation