flutter 写一个screen_util类,目的是适配屏幕
时间: 2024-02-18 13:01:01 浏览: 117
好的,以下是一个简单的 ScreenUtil 类,可以用于 Flutter 屏幕适配:
```dart
import 'package:flutter/material.dart';
class ScreenUtil {
static late double _screenWidth;
static late double _screenHeight;
static late double _pixelRatio;
static late double _statusBarHeight;
static late double _bottomBarHeight;
static late double _textScaleFactor;
static void init(BuildContext context) {
MediaQueryData mediaQuery = MediaQuery.of(context);
_screenWidth = mediaQuery.size.width;
_screenHeight = mediaQuery.size.height;
_pixelRatio = mediaQuery.devicePixelRatio;
_statusBarHeight = mediaQuery.padding.top;
_bottomBarHeight = mediaQuery.padding.bottom;
_textScaleFactor = mediaQuery.textScaleFactor;
}
static double get screenWidth => _screenWidth;
static double get screenHeight => _screenHeight;
static double get pixelRatio => _pixelRatio;
static double get statusBarHeight => _statusBarHeight;
static double get bottomBarHeight => _bottomBarHeight;
static double get textScaleFactor => _textScaleFactor;
static double setWidth(double width) => width * _screenWidth / 375;
static double setHeight(double height) => height * _screenHeight / 667;
static double setSp(double fontSize) => fontSize * _textScaleFactor;
static double setBorderRadius(double radius) => radius * _pixelRatio;
}
```
使用方法:
在 MaterialApp 的 build 方法中调用 ScreenUtil.init(context),初始化 ScreenUtil 类。
```dart
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
ScreenUtil.init(context);
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
```
在布局中使用 ScreenUtil.setWidth、ScreenUtil.setHeight 和 ScreenUtil.setSp 方法来适配宽度、高度和字体大小。
```dart
Container(
width: ScreenUtil.setWidth(100),
height: ScreenUtil.setHeight(100),
margin: EdgeInsets.only(top: ScreenUtil.setHeight(20)),
padding: EdgeInsets.symmetric(horizontal: ScreenUtil.setWidth(20)),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(ScreenUtil.setBorderRadius(10)),
color: Colors.grey[200],
),
child: Text(
'Hello, World!',
style: TextStyle(fontSize: ScreenUtil.setSp(16)),
),
),
```
阅读全文