Flutter ScreenUtil: Adaptive UI for Different Screen Sizes
Published on by Flutter News Hub
Flutter ScreenUtil is a powerful Flutter plugin that simplifies the process of adapting your app's UI layout and font sizes to different screen sizes. It ensures that your app maintains a consistent and visually appealing appearance across a wide range of devices.
Key Features:
- Automatic Screen Size Adaptation: ScreenUtil calculates the actual screen size and provides convenient methods to convert design-time dimensions (in dp) to device-specific pixel values.
- Font Size Adaptation: Easily adjust font sizes to match the system's font size accessibility option or specify custom scaling factors.
- Responsive Widgets: Mark specific widgets for automatic rebuilding when screen size changes, allowing for more granular control over UI responsiveness.
Usage:
- Add Dependency:
dependencies: flutter_screenutil: ^5.9.0
- Import Library:
import 'package:flutter_screenutil/flutter_screenutil.dart';
- Initialize and Configure: Set the design size (width and height) of your app's UI draft and customize other options as needed:
void main() { ScreenUtil.init(context, designSize: const Size(360, 690)); }
API:
Screen Size Conversion:
ScreenUtil().setWidth(540) // Adapt to screen width ScreenUtil().setHeight(200) // Adapt to screen height ScreenUtil().radius(200) // Adapt to smaller of width or height ScreenUtil().scaleWidth // Ratio of actual width to UI design ScreenUtil().scaleHeight // Ratio of actual height to UI design
Font Size Adaptation:
ScreenUtil().setSp(24) // Set font size in sp (scalable pixels) ScreenUtil().sm // Return min(12, 12.sp)
Example:
Adapt a button's width and font size:
Container( width: 50.w, // 50 dp wide height: 200.h, // 200 dp high child: Text( "Button", style: TextStyle( fontSize: 16.sp, // 16 sp font size ), ), )
Benefits:
- Consistent UI: Provides a consistent and visually appealing UI across different screen sizes and resolutions.
- Efficient Development: Simplifies the process of adapting UI to various devices, saving developers time and effort.
- Platform Agnostic: Compatible with iOS and Android platforms, ensuring seamless cross-platform UI experiences.
Additional Notes:
- The design size should be based on the actual screen size used in the design draft.
- You can customize the fontSizeResolver function to specify how font sizes should be scaled.
- ScreenUtilInit will automatically mark widgets for rebuilding based on their names and type.
By utilizing Flutter ScreenUtil, you can effortlessly create adaptive and responsive UI layouts for your Flutter apps, enhancing the user experience and ensuring a consistent appearance on any device.