Flutter获取手机网络信息插件nr_cellinfo的使用
Flutter获取手机网络信息插件nr_cellinfo的使用
nr_cellinfo
A new flutter plugin project.
获取开始
此项目是一个用于Flutter的插件包起点,它包含针对Android和/或iOS的平台特定实现代码。
对于如何开始使用Flutter的帮助,请查看我们的在线文档,其中包含教程、示例、移动开发指南以及完整的API参考。
使用示例
以下是一个完整的示例,展示如何在Flutter应用中使用nr_cellinfo
插件来获取手机网络信息。
示例代码
example/lib/main.dart
// ignore_for_file: avoid_print
import 'dart:convert';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:nr_cellinfo/cellResponse.dart'; // 导入网络信息响应类
import 'package:nr_cellinfo/simInfoResponse.dart'; // 导入SIM卡信息响应类
import 'package:nr_cellinfo/nr_cellinfo.dart'; // 导入核心插件
import 'package:nr_cellinfo/models/common/cell_type.dart'; // 导入网络类型枚举
void main() {
runApp(const MyApp()); // 启动应用
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState(); // 初始化状态
}
class _MyAppState extends State<MyApp> {
CellsResponse? _cellsResponse; // 存储网络信息响应
@override
void initState() {
super.initState();
initPlatformState(); // 初始化平台状态
}
String currentDBM = ""; // 当前信号强度变量
// 平台消息是异步的,因此我们在异步方法中初始化
Future<void> initPlatformState() async {
CellsResponse? cellsResponse;
// 平台消息可能会失败,因此我们使用try/catch捕获PlatformException
try {
// 获取网络信息
String platformVersion = (await NrCellinfo.getCellInfo) ?? "";
final body = json.decode(platformVersion); // 解析JSON
cellsResponse = CellsResponse.fromJson(body); // 转换为对象
// 获取主小区的信号强度
CellType currentCellInFirstChip = cellsResponse.primaryCellList![0];
if (currentCellInFirstChip.type == "LTE") {
currentDBM = "LTE dbm = " +
currentCellInFirstChip.lte!.signalLTE!.dbm.toString();
} else if (currentCellInFirstChip.type == "NR") {
currentDBM =
"NR dbm = " + currentCellInFirstChip.nr!.signalNR!.dbm.toString();
} else if (currentCellInFirstChip.type == "WCDMA") {
currentDBM = "WCDMA dbm = " +
currentCellInFirstChip.wcdma!.signalWCDMA!.dbm.toString();
}
// 打印当前信号强度
print('currentDBM = ' + currentDBM);
// 获取SIM卡信息
String simInfo = (await NrCellinfo.getSIMInfo) ?? "";
final simJson = json.decode(simInfo);
print(
"display name ${SIMInfoResponse.fromJson(simJson).simInfoList![0].displayName}");
} on PlatformException {
_cellsResponse = null;
}
// 如果小部件从树中移除时异步平台消息仍在飞行,则丢弃回复而不是调用setState更新非存在的外观
if (!mounted) return;
setState(() {
_cellsResponse = cellsResponse; // 更新UI
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'), // 设置标题
),
body: _cellsResponse != null
? Center(
child: Text(
'david = $currentDBM\n primary = ${_cellsResponse!.primaryCellList!.length.toString()} \n neighbor = ${_cellsResponse!.neighboringCellList!.length}', // 显示网络信息
),
)
: null,
),
);
}
}
运行效果
运行上述代码后,您将看到类似以下的界面:
david = NR dbm = -70
primary = 1
neighbor = 3
更多关于Flutter获取手机网络信息插件nr_cellinfo的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复