Flutter环境信息获取插件flutter_environment的使用

Flutter环境信息获取插件flutter_environment的使用

安装

  1. 在你的项目pubspec.yaml文件中添加以下依赖:
dependencies:
  flutter_environment: ^latest_version
  1. 使用命令行安装它:
$ flutter pub get
  1. 在Dart代码中导入:
import 'package:flutter_environment/flutter_environment.dart';

使用

在你的主函数中设置flutter_environment,我们建议你在主函数的顶部设置它,以便可以在应用的任何位置使用Environment.instance

void main() {
  EnvironmentType environmentType = EnvironmentConfig.environmentType;
  Environment(
    environmentType: environmentType,
    color: Colors.red.shade900,
    values: EnvironmentValues(
      environmentType == EnvironmentType.dev
          ? 'https://www.duckma.org'
          : 'https://www.duckma.com',
    ),
  );

  // 打印环境信息
  debugPrint('Is development environment: ${Environment.isDevelopment}');
  debugPrint('Is alpha environment: ${Environment.isAlpha}');
  debugPrint('Is beta environment: ${Environment.isBeta}');
  debugPrint('Is production environment: ${Environment.isProduction}');
  debugPrint(Environment.instance.values.baseUrl);

  runApp(const MyApp());
}

为了根据environmentType设置值,可以使用Environment.instance.environment并使用switch语句:

String _getSomeValue(EnvironmentType environmentType) {
  switch (environmentType) {
    case EnvironmentType.dev:
    case EnvironmentType.alpha:
      return 'Users angry';
    case EnvironmentType.beta:
    case EnvironmentType.prod:
      return 'Users happy';
  }
}

注意:这不适用于EnvironmentValues.baseUrl,因为Environment尚未初始化,所以我们使用EnvironmentConfig.environmentType

如果你需要更多的EnvironmentValues,可以通过扩展EnvironmentValues来实现。我们这样做是因为单例静态getter无法处理类型参数。

extension EnvironmentValuesE on EnvironmentValues {
  String get envKey => 'DEV';

  String get userStatus => _getSomeValue(Environment.instance.environment);
}

获取信息

你可以通过以下方式获取当前的EnvironmentType信息:

print('Is development environment: ${Environment.isDevelopment}');
print('Is alpha environment: ${Environment.isAlpha}');
print('Is beta environment: ${Environment.isBeta}');
print('Is production environment: ${Environment.isProduction}');

例如,在API类中使用:

class Api {
  final baseUrl = Environment.instance.values.baseUrl;
}

完整示例

以下是完整的示例代码:

// Copyright (c) 2022 DuckMa Srl. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.

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

String _getSomeValue(EnvironmentType environmentType) {
  switch (environmentType) {
    case EnvironmentType.dev:
    case EnvironmentType.alpha:
      return 'Users angry';
    case EnvironmentType.beta:
    case EnvironmentType.prod:
      return 'Users happy';
  }
}

extension EnvironmentValuesE on EnvironmentValues {
  String get envKey => 'DEV';

  String get userStatus => _getSomeValue(Environment.instance.environment);
}

void main() {
  EnvironmentType environmentType = EnvironmentConfig.environmentType;
  Environment(
    environmentType: environmentType,
    color: Colors.red.shade900,
    values: EnvironmentValues(
      environmentType == EnvironmentType.dev
          ? 'https://www.duckma.org'
          : 'https://www.duckma.com',
    ),
  );

  debugPrint('Is development environment: ${Environment.isDevelopment}');
  debugPrint('Is alpha environment: ${Environment.isAlpha}');
  debugPrint('Is beta environment: ${Environment.isBeta}');
  debugPrint('Is production environment: ${Environment.isProduction}');
  debugPrint(Environment.instance.values.baseUrl);

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return EnvironmentBanner(
      child: Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text(
                'You have pushed the button this many times:',
              ),
              Text(
                '$_counter',
                style: Theme.of(context).textTheme.headline4,
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _incrementCounter,
          tooltip: 'Increment',
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}

更多关于Flutter环境信息获取插件flutter_environment的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter环境信息获取插件flutter_environment的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


flutter_environment 是一个用于获取 Flutter 应用环境信息的插件。它可以帮助你轻松地获取应用的构建环境、版本信息、包名等。以下是如何使用 flutter_environment 插件的步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  flutter_environment: ^1.0.0  # 请使用最新版本

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

2. 导入插件

在你的 Dart 文件中导入 flutter_environment 插件:

import 'package:flutter_environment/flutter_environment.dart';

3. 获取环境信息

你可以通过 FlutterEnvironment 类来获取各种环境信息。以下是一些常用的方法:

  • 获取应用包名

    String packageName = await FlutterEnvironment.packageName;
    print('Package Name: $packageName');
    
  • 获取应用版本

    String version = await FlutterEnvironment.version;
    print('Version: $version');
    
  • 获取应用构建号

    String buildNumber = await FlutterEnvironment.buildNumber;
    print('Build Number: $buildNumber');
    
  • 获取应用名称

    String appName = await FlutterEnvironment.appName;
    print('App Name: $appName');
    
  • 获取应用图标

    String appIcon = await FlutterEnvironment.appIcon;
    print('App Icon: $appIcon');
    
  • 获取应用运行的平台

    String platform = await FlutterEnvironment.platform;
    print('Platform: $platform');
    

4. 使用示例

以下是一个完整的示例,展示了如何获取并打印应用的环境信息:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  String packageName = await FlutterEnvironment.packageName;
  String version = await FlutterEnvironment.version;
  String buildNumber = await FlutterEnvironment.buildNumber;
  String appName = await FlutterEnvironment.appName;
  String appIcon = await FlutterEnvironment.appIcon;
  String platform = await FlutterEnvironment.platform;

  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: Text('Flutter Environment Info'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Package Name: $packageName'),
            Text('Version: $version'),
            Text('Build Number: $buildNumber'),
            Text('App Name: $appName'),
            Text('App Icon: $appIcon'),
            Text('Platform: $platform'),
          ],
        ),
      ),
    ),
  ));
}
回到顶部