flutter_screenutil
repository·master·Indexed 26 days ago
https://github.com/openflutter/flutter_screenutilA Flutter plugin designed to adapt screen and font sizes to ensure UI layouts remain consistent across different device screen sizes. It provides tools for scaling dimensions (w, h, r, sw, sh) and font sizes (sp), along with responsive widgets like RPadding, REdgeInsets, and RSizedBox. The library includes ScreenUtilInit for initialization and supports advanced rebuild logic and font size resolution strategies.
What's inside flutter_screenutil
- flutter_screenutil is a Flutter plugin designed for screen size and font adaptation. It allows your UI to display an acceptable layout across different screen sizes by scaling dimensions and fonts.
Initialize ScreenUtil for Hybrid/Theme Support
masterIf you need to support font adaptation within the
textThemeof an app theme (common in hybrid development), use the second initialization method:- Call
await ScreenUtil.ensureScreenSize();in yourmain()function. - Use
ScreenUtil.init(context)inside thebuilderof yourMaterialApp.
void main() async { // Add this line await ScreenUtil.ensureScreenSize(); runApp(MyApp()); } // Inside MaterialApp builder builder: (ctx, child) { ScreenUtil.init(ctx); return Theme( data: ThemeData( primarySwatch: Colors.blue, textTheme: TextTheme(bodyText2: TextStyle(fontSize: 30.sp)), ), child: HomePage(title: 'FlutterScreenUtil Demo'), ); }- Call
Prevent font scaling with system accessibility settings
masterBy default,
.spscales with the system's font size accessibility settings. To prevent this and keep font sizes constant, you can either settextScaleFactor: 1.0on a specificTextwidget or wrap a widget tree in aMediaQuerythat overrides thetextScaleFactor.// Option 1: For a single Text widget Text("text", textScaleFactor: 1.0) // Option 2: For a specific widget subtree MediaQuery( data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0), child: AnyWidget(), ) // Option 3: Globally in MaterialApp builder MaterialApp( builder: (context, widget) { return MediaQuery( data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0), child: widget, ); }, home: HomePage(), )Initialize ScreenUtil using ScreenUtilInit
masterThe recommended way to initialize the library is using the
ScreenUtilInitwidget at the root of your application (e.g., in yourMaterialApp). This allows you to set thedesignSize(the dimensions of your UI design draft in dp) and provides abuilderto construct your app.Key properties:
designSize: The size of the device screen in the design draft (e.g.,Size(360, 690)).minTextAdapt: Whether to adapt text according to the minimum of width and height.splitScreenMode: Support for split screen mode.builder: A function returning aWidget(usuallyMaterialApp).
void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return ScreenUtilInit( designSize: Size(360, 690), minTextAdapt: true, splitScreenMode: true, builder: () => MaterialApp( // ... other code builder: (context, widget) { // Add this line to make ScreenUtil sensitive to screen changes ScreenUtil.setContext(context); return MediaQuery( // Setting font does not change with system font size data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0), child: widget!, ); }, ), ); } }Initialize ScreenUtil manually with ScreenUtil.init
masterFor hybrid development or specific use cases where
ScreenUtilInitis not used, you can manually initialize the library usingScreenUtil.init. This is typically done within abuildmethod or aStatefulWidget'sinitStateusingBoxConstraintsfrom aLayoutBuilderorMediaQuery.@override Widget build(BuildContext context) { ScreenUtil.init( BoxConstraints( maxWidth: MediaQuery.of(context).size.width, maxHeight: MediaQuery.of(context).size.height), designSize: Size(360, 690), context: context, orientation: Orientation.portrait); return Scaffold(); }Customize iOS Launch Screen Assets
masterTo customize the iOS launch screen, you can either replace the image files directly in the
example/ios/Runner/Assets.xcassets/LaunchImage.imageset/directory or use Xcode for a visual approach:- Open the iOS project in Xcode using the command:
open ios/Runner.xcworkspace. - In the Project Navigator, select
Runner/Assets.xcassets. - Drag and drop your desired images into the asset catalog.
open ios/Runner.xcworkspace- Open the iOS project in Xcode using the command:
Initialize ScreenUtil manually for hybrid or specific use cases
masterIf you cannot use
ScreenUtilInit(e.g., in hybrid development or when you need to support text adaptation in themes manually), you can initialize it usingScreenUtil.ensureScreenSize()inmainand callingScreenUtil.init(context, designSize: ...)within abuilderor abuildmethod.void main() async { await ScreenUtil.ensureScreenSize(); runApp(MyApp()); } // Inside MaterialApp builder or a Widget's build method: ScreenUtil.init(context, designSize: const Size(360, 690));Install flutter_screenutil
masterAdd
flutter_screenutilto yourpubspec.yamldependencies. Check for the latest version before installing.dependencies: flutter: sdk: flutter flutter_screenutil: ^{latest version}dependencies: flutter: sdk: flutter # add flutter_screenutil flutter_screenutil: ^{latest version}Initialize ScreenUtilInit
masterThe recommended way to initialize the library is using the
ScreenUtilInitwidget. You must provide either abuilder, achild, or both. Set thedesignSizeto match your UI design dimensions in dp.Key properties:
designSize: The size of the device screen in the design draft (e.g.,Size(360, 690)).minTextAdapt: Whether to adapt text according to the minimum of width and height.splitScreenMode: Enables support for split screen.builder: A function to return a widget that uses the library (e.g.,MaterialApp).
return ScreenUtilInit( designSize: const Size(360, 690), minTextAdapt: true, splitScreenMode: true, builder: (_ , child) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'First Method', theme: ThemeData( primarySwatch: Colors.blue, textTheme: Typography.englishLike2018.apply(fontSizeFactor: 1.sp), ), home: child, ); }, child: const HomePage(title: 'First Method'), );Initialize ScreenUtil
masterTo use
ScreenUtilfor adaptive sizing, you must initialize it with your UI design dimensions. You can useScreenUtil.initwithin a widget tree orScreenUtil.ensureScreenSizeAndInitto wait for the window size to be available (recommended for splash screens or bootstrap logic).Common parameters:
designSize: The size of the phone in your UI design (default isSize(360, 690)).splitScreenMode: Whether to handle split-screen mode.minTextAdapt: Whether to adapt text based on the smaller scale factor.fontSizeResolver: A custom function to resolve font sizes.
Widget testing with ScreenUtil (Version 5.9.0+)
masterWhen writing widget tests that depend on
flutter_screenutil, you must usetester.pumpAndSettle()to ensure animations and state changes settle correctly and to avoid unexpected errors.testWidgets('Should ensure widgets settle correctly', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: ScreenUtilInit( child: MyApp(), ), ), ); await tester.pumpAndSettle(); // Continue with assertions });Enable or disable scaling
masterYou can globally enable or disable scaling for width/height and text viaScreenUtilInitproperties or theScreenUtil.enableScalemethod.