Flutter屏幕辅助插件screen_helper的使用

Flutter屏幕辅助插件screen_helper的使用

screen_helper

Pub Version GitHub last commit GitHub Issues or Pull Requests GitHub repo size

A package that provides essential tools for Flutter developers to access device screen details, including PPI, screen size in inches, resolution in pixels, and conversion from millimeters to pixels.

Table of Contents

Features

  • Get screen PPI (Pixels Per Inch).
  • Get screen width and height and diagonal size in pixels.
  • Get screen width and height and diagonal size in inches.
  • Convert millimeters to pixels and vice versa.
  • Convert inches to pixels and vice versa.
  • Convert centimeters to pixels and vice versa.
App example

Getting Started

在你的flutter项目中添加依赖:

dependencies:
  screen_helper: ^1.0.1

Usage

在你的应用中包裹 ScreenHelperWidget 来提供屏幕信息给所有后代小部件:

import 'package:screen_helper/screen_helper.dart';

void main() {
  runApp(
    /// 包裹你的应用以提供屏幕信息给所有后代小部件
    ScreenHelperWidget(
      child: const MyApp(),
    ),
  );
}

访问屏幕信息

要获取屏幕信息,可以使用 ScreenInfo.maybeOf(context)

final screenInfo = ScreenInfo.maybeOf(context);

可用数据

/// 获取屏幕尺寸(宽和高)以英寸为单位
final Map<String, double> screenSizeInInches = screenInfo.screenSizeInInches;

/// 获取屏幕分辨率(宽和高)以像素为单位
final Map<String, double> screenResolution = screenInfo.screenResolution;

/// 获取屏幕的每英寸点数(DPI)
final double dpi = screenInfo.dpi;

/// 获取屏幕的每英寸像素数(PPI)
final double ppi = screenInfo.ppi;

/// 获取屏幕宽度(以英寸为单位)
final double screenWidthInInches = screenInfo.screenWidthInInches;

/// 获取屏幕高度(以英寸为单位)
final double screenHeightInInches = screenInfo.screenHeightInches;

/// 获取屏幕对角线大小(以英寸为单位)
final double screenDiagonalInInches = screenInfo.screenDiagonalInInches;

/// 获取屏幕宽度(以像素为单位)
final double screenWidthInPixels = screenInfo.screenWidthInPixels;

/// 获取屏幕高度(以像素为单位)
final double screenHeightInPixels = screenInfo.screenHeightInPixels;

/// 获取屏幕宽高比
final double screenAspectRatio = screenInfo.screenAspectRatio;

单位转换

为了在不同单位之间进行转换,你可以使用 BuildContext 上的扩展方法:

// 在构建方法中访问 BuildContext
Widget build(BuildContext context) {
  // 将毫米转换为像素
  double mmToPx = context.mmToPx(double mm);
  // 将像素转换为毫米
  double pxToMm = context.pxToMm(int px);
  // 将厘米转换为像素
  double cmToPx = context.cmToPx(double cm);
  // 将像素转换为厘米
  double pxToCm = context.pxToCm(int px);
  // 将英寸转换为像素
  double inchesToPx = context.inchesToPx(double inches);
  // 将像素转换为英寸
  double pxToInches = context.pxToInches(int px);
}

Example

以下是一个完整的示例:

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    // 包裹你的应用以提供屏幕信息给所有后代小部件
    return ScreenHelperWidget(
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          appBar: AppBar(
            title: const Text('Screen Helper Example App'),
          ),
          body: const Center(
            child: Padding(
              padding: EdgeInsets.all(16.0),
              child: ScreenInfoDisplay(),
            ),
          ),
        ),
      ),
    );
  }
}

class ScreenInfoDisplay extends StatefulWidget {
  const ScreenInfoDisplay({super.key});

  [@override](/user/override)
  State<ScreenInfoDisplay> createState() => _ScreenInfoDisplayState();
}

class _ScreenInfoDisplayState extends State<ScreenInfoDisplay> {
  double _lineLengthMm = 15.0;

  [@override](/user/override)
  Widget build(BuildContext context) {
    // 使用 ScreenInfo.of(context) 获取屏幕信息
    final screenInfo = ScreenInfo.maybeOf(context);
    if (screenInfo == null) {
      return const CircularProgressIndicator();
    }

    // 使用扩展方法将毫米转换为像素
    final lineLengthInPixels = context.mmToPx(_lineLengthMm);

    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        // 显示各种屏幕属性
        Text(
          'Screen PPI: ${screenInfo.ppi.toStringAsFixed(2)}',
          style: const TextStyle(fontSize: 16),
        ),
        const SizedBox(height: 10),
        Text(
          'Screen Diagonal Size (in inches): ${screenInfo.screenDiagonalInInches.toStringAsFixed(2)}',
          style: const TextStyle(fontSize: 16),
        ),
        const SizedBox(height: 10),
        Text(
          'Screen Width (in inches): ${screenInfo.screenWidthInInches.toStringAsFixed(2)}',
          style: const TextStyle(fontSize: 16),
        ),
        const SizedBox(height: 10),
        Text(
          'Screen Height (in inches): ${screenInfo.screenHeightInches.toStringAsFixed(2)}',
          style: const TextStyle(fontSize: 16),
        ),
        const SizedBox(height: 10),
        Text(
          'Screen Real Width (in pixels): ${screenInfo.screenWidthInPixels.toStringAsFixed(0)}',
          style: const TextStyle(fontSize: 16),
        ),
        const SizedBox(height: 10),
        Text(
          'Screen Real Height (in pixels): ${screenInfo.screenHeightInPixels.toStringAsFixed(0)}',
          style: const TextStyle(fontSize: 16),
        ),
        const SizedBox(height: 20),
        Text(
          "Line length: ${_lineLengthMm.toStringAsFixed(1)} mm",
          style: const TextStyle(fontSize: 16),
        ),
        Slider(
          value: _lineLengthMm,
          min: 1,
          max: 100,
          divisions: 99,
          label: _lineLengthMm.round().toString(),
          onChanged: (double value) {
            setState(() {
              _lineLengthMm = value;
            });
          },
        ),
        const SizedBox(height: 10),
        Text(
          "Line length in pixels: ${lineLengthInPixels.toStringAsFixed(2)}",
          style: const TextStyle(fontSize: 16),
        ),
        const SizedBox(height: 10),
        // 显示一个具有转换长度的线段
        Center(
          child: Container(
            width: lineLengthInPixels,
            height: 2.0,
            color: Colors.black,
          ),
        ),
      ],
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用screen_helper插件的代码示例。screen_helper插件通常用于获取屏幕尺寸、屏幕密度等信息,以便更好地适配不同设备。

首先,你需要在pubspec.yaml文件中添加screen_helper依赖:

dependencies:
  flutter:
    sdk: flutter
  screen_helper: ^x.y.z  # 请将x.y.z替换为最新版本号

然后运行flutter pub get来安装依赖。

接下来,在你的Flutter项目中,你可以这样使用screen_helper插件:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Screen Helper Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ScreenHelperDemo(),
    );
  }
}

class ScreenHelperDemo extends StatefulWidget {
  @override
  _ScreenHelperDemoState createState() => _ScreenHelperDemoState();
}

class _ScreenHelperDemoState extends State<ScreenHelperDemo> {
  ScreenHelper? _screenHelper;

  @override
  void initState() {
    super.initState();
    // 初始化ScreenHelper
    _screenHelper = ScreenHelper();
    _screenHelper!.init(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Screen Helper Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Screen Width: ${_screenHelper!.screenWidth.toDouble().toStringAsFixed(2)} px',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 20),
            Text(
              'Screen Height: ${_screenHelper!.screenHeight.toDouble().toStringAsFixed(2)} px',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 20),
            Text(
              'Screen Density: ${_screenHelper!.screenDensity.toDouble().toStringAsFixed(2)}',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 20),
            Text(
              'Text Scale Factor: ${_screenHelper!.textScaleFactor.toDouble().toStringAsFixed(2)}',
              style: TextStyle(fontSize: 20),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们做了以下几件事:

  1. pubspec.yaml中添加screen_helper依赖。
  2. 在主应用中初始化ScreenHelper实例,并调用init(context)方法。
  3. 在UI中展示屏幕尺寸、屏幕密度、文本缩放因子等信息。

请注意,screen_helper插件的具体API可能会随着版本更新而有所变化,因此建议查阅最新的官方文档(假设该插件在pub.dev上有文档)以获取最准确的信息。

此外,如果screen_helper插件的API有所调整,比如初始化方法或属性访问方式有所变化,你需要根据最新文档进行相应的调整。

回到顶部