Flutter屏幕自适应像素封装

本文介绍了如何使用 ScreenAadpt 类进行 Flutter 应用的屏幕自适应设计,包括获取设备尺寸、计算设计稿像素、以及容器布局的实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import 'dart:ui';

import 'package:flutter/material.dart';

//自适应屏幕
class ScreenAadpt {
  //第一步 获取设备对象属性
  static MediaQueryData mediaQuery = MediaQueryData.fromWindow(window);
  static double screenwidth; //设备屏幕宽度width
  static double screenheight; //设备屏幕高度height
  static double topheight; //顶部空白高度
  static double bottomheight; //底部空白高度
  static double devicepixelratio = mediaQuery.devicePixelRatio; //分辨比
  static var screenratio; //屏幕宽比

  //初始化 UI设计稿:比如750、1920等  uinumber变量设计稿宽
  static initialize(int uinumber) {
    screenwidth = mediaQuery.size.width;
    screenheight = mediaQuery.size.height;
    int uiwidth = uinumber is int ? uinumber : 1920; //默认是1920 ui设计图
    screenratio = screenwidth / uiwidth; //屏幕宽比  设备宽度 : ui设计图宽度
  }

  //实现填写像素  number:设计稿的像素
  static px(number) {
    if (!(screenratio is double || screenratio is int)) {
      ScreenAadpt.initialize(1920);
    }
    return number * screenratio; //返回处理好的像素数值
  }

  //获取屏幕宽度
  static screenWidth() {
    screenwidth = mediaQuery.size.width;
    return screenwidth;
  }

  //获取设备屏幕高度
  static screenHeight() {
    screenheight = mediaQuery.size.height;
    return screenheight;
  }

  //获取设备顶部空白高度
  static topHeight() {
    topheight = mediaQuery.padding.top;
    return topheight;
  }

  //获取设备底部空白高度
  static bottomHeight() {
    bottomheight = mediaQuery.padding.bottom;
    return bottomheight;
  }
}

例子:

Container(
          width: ScreenAadpt.px(168),//使用组件
          height: ScreenAadpt.px(168),//使用组件
          alignment: Alignment.center,
          decoration: BoxDecoration(
              border: Border.all(
                  color: Color.fromRGBO(66, 66, 66, 1),
                  width: ScreenAadpt.px(6)),
              shape: BoxShape.circle,
              color: Color.fromRGBO(255, 255, 255, 1)),
        ),
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值