Flutter屏幕适配插件responsify的使用

Flutter屏幕适配插件responsify的使用

概述

responsify 包是一个基于 Dart 的 Flutter 包,用于根据设备类型创建响应式用户界面。此包基于 FilledStacks 的教程。

使用此库,您可以:

  • 获取设备类型(移动设备、平板电脑、计算机或可穿戴设备)并根据不同设备类型创建不同的布局。
  • 获取设备的方向。
  • 获取设备的平台亮度(亮色模式或暗色模式)。
  • 获取父级小部件的大小(宽 × 高)。
  • 获取子级小部件的大小(宽 × 高)。
  • 获取设备的操作系统作为字符串。

这个库如何工作

库包含一个名为 ResponsiveUiWidget 的单一小部件,该小部件在 build 方法中返回一个小部件。

  • 库考虑了设备的像素密度。像素密度通过设备的像素比和基准像素密度 160 来确定。较旧的计算机具有较低的像素密度(如 96 或 120 ppi)。在这种情况下,当确定设备是否为计算机时不会考虑像素密度。

  • ResponsiveUiWidget 有一个名为 targetOlderComputers 的必需参数。如果为 true,则此标志允许您针对具有低于 160 像素密度的较旧计算机模型。当为 true 时,只有此标志和计算机的平台操作系统(Windows、macOS、Linux)用于确定设备是否为计算机。如果为 false,则使用勾股定理(见下一点)和平台操作系统来确定设备类型。

  • 使用勾股定理计算设备屏幕的对角线尺寸(以像素为单位)。然后使用设备的像素密度将此值转换为对角线屏幕尺寸(英寸)。设备屏幕尺寸(英寸) = 设备屏幕尺寸(像素) / 设备像素密度(PPI)。然后与设备的平台操作系统一起用于确定设备类型(移动设备、平板电脑、可穿戴设备、计算机)。

如果上述三点听起来很复杂,这里有一个代码块:

bool checkHandheldDevicePlatform = Platform.isAndroid || Platform.isIOS || Platform.isFuchsia;

bool checkComputerPlatform = Platform.isWindows || Platform.isMacOS || Platform.isLinux;

if (deviceSize! <= 3) {
  return deviceType = DeviceTypeInformation.WEARABLE;
} else if (deviceSize! > 3 && deviceSize! < 7.1 && checkHandheldDevicePlatform) {
  return deviceType = DeviceTypeInformation.MOBILE;
} else if (deviceSize! > 7.1 && deviceSize! < 13.5 && checkHandheldDevicePlatform) {
  return deviceType = DeviceTypeInformation.TABLET;
} else if ((deviceSize! > 13.5 && deviceSize! < 55 && checkComputerPlatform) ||
    (targetOlderComputers! && checkComputerPlatform)) {
  return deviceType = DeviceTypeInformation.COMPUTER;
} else {
  return deviceType = DeviceTypeInformation.UNKNOWN;
}
  • 设备像素密度 = 设备像素比 * 160。设备像素比通过 MediaQuery 获取。

  • 设备屏幕尺寸的阈值是通过搜索每种设备类型的最小和最大屏幕尺寸来确定的。因此,您无需指定设备尺寸的阈值。

使用方法

  1. responsify 添加到您的 pubspec.yaml 文件中,并运行 pub get

  2. 导入 responsify.dart 文件到您的项目中,例如:

    import 'package:responsify/responsify.dart';
    
  3. 使用它。例如:

    class DeviceInformation extends StatelessWidget {
      DeviceInformation({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Center(
          child: ResponsiveUiWidget(
            targetOlderComputers: true,
            builder: (context, deviceInformation) {
              @override
              String toString() {
                return "Device Type: ${deviceInformation.deviceTypeInformation}\n"
                    "Device OS: ${deviceInformation.deviceOS}\n"
                    "Device Orientation: ${deviceInformation.orientation}\n"
                    "Platform Brightness: ${deviceInformation.platformBrightness}\n"
                    "Parent Widget Size: ${deviceInformation.parentWidgetSize}\n"
                    "Local Widget Size (W x H): ${deviceInformation.localWidgetWidth} x ${deviceInformation.localWidgetHeight}";
              }
    
              return Text(
                toString(),
                style: TextStyle(fontSize: deviceInformation.deviceTypeInformation == DeviceTypeInformation.WEARABLE ? 8 : 16),
              );
            },
          ),
        );
      }
    }
    
  4. 另一个示例,使用 MaterialPageRoutePageRouteBuilder

    class ResponsifyApp extends StatelessWidget {
      ResponsifyApp({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Center(
          child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
            MaterialButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => ResponsiveUiWidget(
                        targetOlderComputers: false,
                        builder: (context, deviceInformation) {
                          if (deviceInformation.deviceTypeInformation == DeviceTypeInformation.MOBILE) {
                            return MobileVersion();
                          } else {
                            return Scaffold(
                              body: Center(
                                child: Text("This app is compatible only with a Mobile device"),
                              ),
                            );
                          }
                        }),
                  ),
                );
              },
              textColor: Colors.white,
              child: Text("Mobile"),
              color: Colors.black,
            ),
            MaterialButton(
              onPressed: () {
                Navigator.push(
                  context,
                  PageRouteBuilder(
                    pageBuilder: (_, __, ___) => ResponsiveUiWidget(
                      targetOlderComputers: false,
                      builder: (context, deviceInformation) {
                        if (deviceInformation.deviceTypeInformation == DeviceTypeInformation.TABLET) {
                          return TabletVersion();
                        } else {
                          return Scaffold(
                            body: Center(
                              child: Text("This app is compatible only with a Tablet device"),
                            ),
                          );
                        }
                      },
                    ),
                  ),
                );
              },
              textColor: Colors.white,
              child: Text("Tablet"),
              color: Colors.black,
            )
          ]),
        );
      }
    }
    
    class MobileVersion extends StatelessWidget {
      const MobileVersion({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(child: Text("This is a Mobile Device")),
        );
      }
    }
    
    class TabletVersion extends StatelessWidget {
      const TabletVersion({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(child: Text("This is a Tablet Device")),
        );
      }
    }
    

更多关于Flutter屏幕适配插件responsify的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter屏幕适配插件responsify的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用responsify插件进行屏幕适配的代码示例。responsify是一个用于简化Flutter屏幕适配的插件,通过定义一套基准尺寸,可以自动调整UI组件的大小以适应不同的屏幕尺寸。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加responsify依赖:

dependencies:
  flutter:
    sdk: flutter
  responsify: ^最新版本号  # 请替换为最新版本号

然后运行flutter pub get来获取依赖。

2. 配置Responsify

在你的项目的主文件(通常是main.dart)中,配置Responsify。你需要定义一个基准尺寸(例如设计稿的尺寸)以及应用的上下文。

import 'package:flutter/material.dart';
import 'package:responsify/responsify.dart';

void main() {
  // 配置Responsify,假设设计稿是基于375x667的iPhone 8
  ResponsifyConfig(
    context: EquatableConfig(
      designWidth: 375,
      designHeight: 667,
    ),
    child: MyApp(),
  ).runApp();
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

3. 使用RespSize和RespValue进行适配

在你的UI组件中,使用RespSizeRespValue来根据屏幕尺寸动态调整大小。

import 'package:flutter/material.dart';
import 'package:responsify/responsify.dart';

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Responsify Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // 使用RespSize来适配容器大小
            Container(
              width: RespSize.width(percentage: 80),  // 宽度为屏幕宽度的80%
              height: RespSize.height(percentage: 40), // 高度为屏幕高度的40%
              color: Colors.blue,
              child: Center(
                child: Text(
                  'Responsive Container',
                  style: TextStyle(color: Colors.white, fontSize: RespValue(18)), // 使用RespValue来适配字体大小
                ),
              ),
            ),
            SizedBox(height: RespSize.height(percentage: 5)), // 间距也进行适配
            // 使用RespValue来适配其他属性,如边距、内边距等
            ElevatedButton(
              onPressed: () {},
              child: Text('Click Me'),
              style: ElevatedButton.styleFrom(
                padding: EdgeInsets.symmetric(
                  horizontal: RespValue(20), // 水平内边距适配
                  vertical: RespValue(10),   // 垂直内边距适配
                ),
                minimumSize: Size(
                  width: RespSize.width(percentage: 60), // 最小宽度适配
                  height: RespValue(40),                 // 最小高度适配
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

总结

通过上述步骤,你可以在Flutter项目中使用responsify插件进行屏幕适配。RespSizeRespValue使得UI组件的大小可以根据不同的屏幕尺寸动态调整,从而确保在不同设备上有一致的用户体验。

请确保你使用的是responsify的最新版本,并查阅其官方文档以获取更多功能和最佳实践。

回到顶部