1.5 config service 配置
代码实现 ConfigService 全局配置管理
第 1 步: 安装依赖包 package_info_plus
| 1
 | flutter pub add package_info_plus
 | 
第 2 步: 创建 ConfigService
lib/common/services/config.dart
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 
 | import 'package:get/get.dart';import 'package:package_info_plus/package_info_plus.dart';
 
 
 class ConfigService extends GetxService {
 
 static ConfigService get to => Get.find();
 
 PackageInfo? _platform;
 String get version => _platform?.version ?? '-';
 
 
 Future<ConfigService> init() async {
 await getPlatform();
 return this;
 }
 
 Future<void> getPlatform() async {
 _platform = await PackageInfo.fromPlatform();
 }
 }
 
 | 
static ConfigService get to => Get.find(); 这是一个单例写法
第 3 步: 创建 Global
lib/global.dart
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 
 | import 'package:flutter/material.dart';import 'package:get/get.dart';
 
 import 'common/index.dart';
 
 class Global {
 static Future<void> init() async {
 WidgetsFlutterBinding.ensureInitialized();
 
 await Future.wait([
 Get.putAsync<ConfigService>(() async => await ConfigService().init()),
 ]).whenComplete(() {
 });
 }
 }
 
 | 
Get.put 方式直接注入
WidgetsFlutterBinding.ensureInitialized(); 这个表示先就行原生端(ios android)插件注册,然后再处理后续操作,这样能保证代码运行正确。
修改 main.dart
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | Future<void> main() async {await Global.init();
 runApp(const MyApp());
 }
 
 class MyApp extends StatelessWidget {
 const MyApp({Key? key}) : super(key: key);
 
 ...
 
 | 
注意这里有个 async 同步的操作,保证 Service 正常初始化。
最后: 在 SplashPage 中调用
| 12
 3
 4
 5
 6
 7
 8
 
 | class SplashPage extends GetView<SplashController> {const SplashPage({Key? key}) : super(key: key);
 
 Widget _buildView() {
 return Center(
 child: Text("SplashPage - ${ConfigService.to.version}"),
 );
 }
 
 | 
注意看这里的 ConfigService.to.version 这是单例的调用,使用很便利。
运行后显示当前版本号
 
提交代码到 git
| 12
 
 | git add .git commit -m "config service"
 
 |