Flutter网页构建信息获取插件build_info_web的使用
Flutter网页构建信息获取插件build_info_web的使用
build_info_web
是 build_info
包在Web平台上的实现。
使用
该包已被官方推荐使用(endorsed federated plugin),因此你可以像使用其他包一样直接使用 build_info
。当你这样使用时,此包会自动包含在你的应用中,因此你无需在 pubspec.yaml
文件中添加它。
但是,如果你需要导入此包以直接使用其API,则应像往常一样将其添加到 pubspec.yaml
文件中。
关于Web版本的实现
Web版本的 build_info
的工作方式如下:
- 调用
Flutter
中的BuildInfo.fromPlatform
方法。 - 使用HEAD或GET方法请求 “version.json” 作为构建日期和时间,并使用
<code>Last-Modified</code>
或<code>Date</code>
响应头值。 - 如果无法从 “version.json” 获取日期和时间,则使用
<code>document.lastModified</code>
的值。
如果无法获取日期和时间,它将为 null
。在Web版本中,安装日期和时间始终为 null
。
完整示例代码
以下是一个完整的示例,展示了如何使用 build_info_web
插件来获取构建信息。
// Copyright 2024 Craftsoft LLC. 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/services.dart';
import 'package:build_info_platform_interface/build_info_data.dart';
import 'package:build_info_web/build_info_web.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
BuildInfoData? _buildInfoData;
final _buildInfoWebPlugin = BuildInfoWeb();
[@override](/user/override)
void initState() {
super.initState();
initPlatformState();
}
// 平台消息是异步的,所以我们通过异步方法进行初始化。
Future<void> initPlatformState() async {
BuildInfoData? buildInfoData;
// 平台消息可能会失败,所以我们使用try/catch捕获PlatformException。
// 我们还处理了消息可能返回null的情况。
try {
buildInfoData = await _buildInfoWebPlugin.fromPlatform();
} on PlatformException catch (e, stackTrace) {
debugPrint(e.message);
debugPrintStack(stackTrace: stackTrace);
}
// 如果小部件在异步平台消息还在飞行时被从树中移除,我们希望丢弃回复而不是调用setState来更新我们的不存在的外观。
if (!mounted) return;
setState(() {
_buildInfoData = buildInfoData;
});
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('插件示例应用'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('构建日期: ${_buildInfoData?.buildDate}'),
Text('安装日期: ${_buildInfoData?.installDate}'),
],
),
),
),
);
}
}
更多关于Flutter网页构建信息获取插件build_info_web的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复