Flutter获取运营商信息插件carrier_info的使用
Flutter获取运营商信息插件carrier_info的使用
📱 Carrier Info
Carrier Info
插件用于从Android和iOS设备获取网络类型、网络代际、移动国家代码等信息。它是基于 js项目 的移植,并改进了现有的 flt_telephony_info 包。
📸 屏幕截图
获取 Android 运营商信息
参考文档:
AndroidCarrierData? carrierInfo = await CarrierInfo.getAndroidInfo();
返回示例:
{
"isVoiceCapable": true,
"isDataEnabled": true,
"subscriptionsInfo": [
{
"mobileCountryCode": "310",
"isOpportunistic": false,
"mobileNetworkCode": "260",
"displayName": "T-Mobile",
"isNetworkRoaming": false,
"simSlotIndex": 0,
"phoneNumber": "+15551234567",
"countryIso": "us",
"subscriptionType": 0,
"cardId": 0,
"isEmbedded": false,
"carrierId": 1,
"subscriptionId": 1,
"simSerialNo": "",
"dataRoaming": 0
}
],
"isDataCapable": true,
"isMultiSimSupported": "MULTISIM_NOT_SUPPORTED_BY_HARDWARE",
"isSmsCapable": true,
"telephonyInfo": [
{
"networkCountryIso": "us",
"mobileCountryCode": "310",
"mobileNetworkCode": "260",
"displayName": "T-Mobile",
"simState": "SIM_STATE_READY",
"isoCountryCode": "us",
"cellId": {
"cid": 47108,
"lac": 8514
},
"phoneNumber": "+15551234567",
"carrierName": "T-Mobile",
"subscriptionId": 1,
"networkGeneration": "4G",
"radioType": "LTE",
"networkOperatorName": "T-Mobile"
}
]
}
获取 iOS 运营商信息
IosCarrierData? carrierInfo = await CarrierInfo.getIosInfo();
返回示例:
{
"carrierData": [
{
"mobileNetworkCode": null,
"carrierAllowsVOIP": true,
"mobileCountryCode": null,
"carrierName": "glo",
"isoCountryCode": null
},
{
"mobileNetworkCode": "20",
"isoCountryCode": "ng",
"carrierAllowsVOIP": true,
"carrierName": "Airtel",
"mobileCountryCode": "621"
}
],
"supportsEmbeddedSIM": false,
"carrierRadioAccessTechnologyTypeList": [
"LTE"
]
}
✨ 贡献
为了使此插件更加标准,需要大量的PR。对于iOS,获取确切的数据使用情况存在永久限制,目前只有一种复杂的方法可以绕过这个限制。
示例代码
以下是一个完整的示例代码,展示了如何在Flutter应用中使用 carrier_info
插件来获取运营商信息。
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:carrier_info/carrier_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
IosCarrierData? _iosInfo;
IosCarrierData? get iosInfo => _iosInfo;
set iosInfo(IosCarrierData? iosInfo) {
setState(() => _iosInfo = iosInfo);
}
AndroidCarrierData? _androidInfo;
AndroidCarrierData? get androidInfo => _androidInfo;
set androidInfo(AndroidCarrierData? carrierInfo) {
setState(() => _androidInfo = carrierInfo);
}
@override
void initState() {
super.initState();
initPlatformState();
}
Future<void> initPlatformState() async {
// 请求权限
await [
Permission.locationWhenInUse,
Permission.phone,
Permission.sms,
].request();
try {
if (Platform.isAndroid) androidInfo = await CarrierInfo.getAndroidInfo();
if (Platform.isIOS) iosInfo = await CarrierInfo.getIosInfo();
} catch (e) {
print(e.toString());
}
}
@override
Widget build(BuildContext context) {
return Material(
color: Colors.transparent,
child: CupertinoApp(
debugShowCheckedModeBanner: false,
home: CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: const Text('Carrier Info example app'),
border: Border.symmetric(
horizontal: BorderSide(
width: 0.5,
color: CupertinoColors.systemGrey2.withOpacity(0.4),
),
),
),
backgroundColor: CupertinoColors.lightBackgroundGray,
child: Platform.isAndroid
? AndroidUI(androidInfo: androidInfo)
: IosUI(iosInfo: iosInfo),
),
),
);
}
}
class IosUI extends StatelessWidget {
const IosUI({
super.key,
this.iosInfo,
});
final IosCarrierData? iosInfo;
@override
Widget build(BuildContext context) {
return ListView(
children: [
const SizedBox(height: 20),
Padding(
padding: const EdgeInsets.all(15),
child: Text(
'CARRIER INFORMATION',
style: TextStyle(
fontSize: 15,
color: CupertinoColors.systemGrey,
),
),
),
HomeItem(
title: 'supportsEmbeddedSIM',
value: '${iosInfo?.supportsEmbeddedSIM}',
isFirst: true,
),
...(iosInfo?.carrierRadioAccessTechnologyTypeList ?? []).map(
(it) => HomeItem(
title: '',
value: it,
),
),
...(iosInfo?.carrierData ?? []).map(
(it) => Column(
children: [
const SizedBox(height: 15),
Text(
'SIM: ${it.carrierName}',
style: TextStyle(
fontSize: 15,
color: CupertinoColors.systemGrey,
),
),
const SizedBox(height: 15),
...it.toMap().entries.map(
(e) => HomeItem(
title: e.key,
value: '${e.value}',
),
)
],
),
),
],
);
}
}
class AndroidUI extends StatelessWidget {
const AndroidUI({
super.key,
this.androidInfo,
});
final AndroidCarrierData? androidInfo;
@override
Widget build(BuildContext context) {
return ListView(
children: [
const SizedBox(height: 20),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(15),
child: Text(
'CARRIER INFORMATION',
style: TextStyle(
fontSize: 15,
color: CupertinoColors.systemGrey,
),
),
),
HomeItem(
title: 'isVoiceCapable',
value: '${androidInfo?.isVoiceCapable}',
isFirst: true,
),
HomeItem(
title: 'isSmsCapable',
value: '${androidInfo?.isSmsCapable}',
),
HomeItem(
title: 'isMultiSimSupported',
value: '${androidInfo?.isMultiSimSupported}',
),
HomeItem(
title: 'isDataCapable',
value: '${androidInfo?.isDataCapable}',
),
HomeItem(
title: 'isDataEnabled',
value: '${androidInfo?.isDataEnabled}',
),
...(androidInfo?.telephonyInfo ?? []).map((it) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 15),
child: Column(
children: [
Text(
'SIM: ${it.phoneNumber} (from telephonyInfo)',
style: TextStyle(
fontSize: 15,
color: CupertinoColors.systemGrey,
),
),
const SizedBox(height: 15),
...(it.toMap()).entries.map(
(val) => HomeItem(
title: '${val.key}',
value: '${val.value}',
),
)
],
),
);
}),
...(androidInfo?.subscriptionsInfo ?? []).map((it) {
return Column(
children: [
Text(
'SIM: ${it.phoneNumber} (from subscriptionsInfo)',
style: TextStyle(
fontSize: 15,
color: CupertinoColors.systemGrey,
),
),
const SizedBox(height: 15),
...(it.toMap()).entries.map(
(val) => HomeItem(
title: '${val.key}',
value: '${val.value}',
),
)
],
);
}),
],
),
],
);
}
}
class HomeItem extends StatelessWidget {
final bool isFirst;
final String title;
final String? value;
const HomeItem({
super.key,
required this.title,
this.value,
this.isFirst = false,
});
@override
Widget build(BuildContext context) {
return Material(
color: Colors.white,
child: InkWell(
onTap: () {},
child: Column(
children: [
if (!isFirst)
Container(height: 0.5, color: Colors.grey.withOpacity(0.3)),
Padding(
padding: const EdgeInsets.all(15),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(title),
Spacer(),
Flexible(
child: Wrap(
alignment: WrapAlignment.start,
crossAxisAlignment: WrapCrossAlignment.start,
children: [
Text(value ?? ''),
],
),
),
],
),
),
],
),
),
);
}
}
String jsonPretty(dynamic _obj) {
String prettyprint;
var obj = _obj;
try {
if (_obj is String) {
obj = json.decode(_obj);
}
if (obj is Map ||
obj is Map<dynamic, dynamic> ||
obj is Map<String, dynamic>) {
const encoder = JsonEncoder.withIndent(' ');
prettyprint = encoder.convert(obj);
} else {
prettyprint = '$obj';
}
} catch (e) {
return _obj;
}
return prettyprint;
}
总结
通过上述代码,您可以轻松地在Flutter应用中集成 carrier_info
插件,以获取Android和iOS设备的运营商信息。请确保在请求数据之前先请求必要的权限。希望这个示例能帮助您更好地理解和使用该插件。如果有任何问题或建议,请随时提出。
更多关于Flutter获取运营商信息插件carrier_info的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter获取运营商信息插件carrier_info的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter项目中使用carrier_info
插件来获取设备运营商信息的代码示例。
首先,确保你已经将carrier_info
插件添加到你的pubspec.yaml
文件中:
dependencies:
flutter:
sdk: flutter
carrier_info: ^x.y.z # 请将x.y.z替换为最新版本号
然后,运行flutter pub get
来安装插件。
接下来,你可以在你的Flutter应用中使用该插件来获取设备的运营商信息。以下是一个完整的示例代码:
import 'package:flutter/material.dart';
import 'package:carrier_info/carrier_info.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Carrier Info Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: CarrierInfoScreen(),
);
}
}
class CarrierInfoScreen extends StatefulWidget {
@override
_CarrierInfoScreenState createState() => _CarrierInfoScreenState();
}
class _CarrierInfoScreenState extends State<CarrierInfoScreen> {
String? carrierName;
String? mobileCountryCode;
String? mobileNetworkCode;
String? isoCountryCode;
String? simSerialNumber;
String? subscriberId;
String? numeric;
@override
void initState() {
super.initState();
_getCarrierInfo();
}
Future<void> _getCarrierInfo() async {
try {
CarrierInfo carrierInfo = await CarrierInfo.loadCarrierInfo();
setState(() {
carrierName = carrierInfo.carrierName;
mobileCountryCode = carrierInfo.mobileCountryCode.toString();
mobileNetworkCode = carrierInfo.mobileNetworkCode.toString();
isoCountryCode = carrierInfo.isoCountryCode;
simSerialNumber = carrierInfo.simSerialNumber;
subscriberId = carrierInfo.subscriberId;
numeric = carrierInfo.numeric;
});
} catch (e) {
print("Error fetching carrier info: $e");
// 可以在这里处理错误,比如显示一个错误消息
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Carrier Info Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Carrier Name: ${carrierName ?? 'Loading...'}'),
Text('Mobile Country Code: ${mobileCountryCode ?? 'Loading...'}'),
Text('Mobile Network Code: ${mobileNetworkCode ?? 'Loading...'}'),
Text('ISO Country Code: ${isoCountryCode ?? 'Loading...'}'),
Text('SIM Serial Number: ${simSerialNumber ?? 'Loading...'}'),
Text('Subscriber ID: ${subscriberId ?? 'Loading...'}'),
Text('Numeric: ${numeric ?? 'Loading...'}'),
],
),
),
);
}
}
在这个示例中,我们创建了一个简单的Flutter应用,该应用在启动时加载并显示设备的运营商信息。我们使用CarrierInfo.loadCarrierInfo()
方法来获取这些信息,并在UI中显示它们。
请注意,根据设备的不同和操作系统的权限设置,某些信息可能无法获取或为空。在实际应用中,你可能需要添加适当的错误处理和用户权限请求逻辑。