Flutter智能设备工具插件smart_device_utils的使用
Flutter智能设备工具插件smart_device_utils的使用
A flutter plugin to get device information such as platform version etc for both android & iOS.
安装
在 pubspec.yaml
文件中添加以下依赖:
smart_device_utils:^0.0.3
安装依赖项,运行以下命令:
$ flutter pub get
使用
首先导入插件:
import 'package:smart_device_utils/smart_device_utils.dart';
然后在您的代码中初始化并获取平台版本信息:
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
final _smartDeviceUtilsPlugin = SmartDeviceUtils();
@override
void initState() {
super.initState();
initPlatformState();
}
// 平台消息是异步的,因此我们通过异步方法进行初始化。
Future<void> initPlatformState() async {
String platformVersion;
// 平台消息可能会失败,所以我们使用一个带有 PlatformException 的 try/catch 块。
// 我们还处理了消息可能返回 null 的情况。
try {
platformVersion = await _smartDeviceUtilsPlugin.getPlatformVersion() ??
'Unknown platform version';
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// 如果小部件从树中被移除时异步平台消息仍在飞行,则我们应该丢弃回复而不是调用 setState 来更新我们的非存在的外观。
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('插件示例应用'),
),
body: Center(
child: Text('运行于: $_platformVersion\n'),
),
),
);
}
}
在 Android 中,您需要添加以下权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
对于目标为 Marshmallow 及以上版本的 Android 应用,需要请求运行时权限。而在 iOS 中则无需指定权限。
贡献
欢迎提交拉取请求。如果您想进行重大更改,请先打开一个问题讨论您想要进行的更改。
开发者
Ghulam Mehmood 😄 🎉
许可证
[MIT]
更多关于Flutter智能设备工具插件smart_device_utils的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复