Flutter获取SIM卡数据插件sim_data_plus的使用

发布于 1周前 作者 h691938207 来自 Flutter

Flutter获取SIM卡数据插件sim_data_plus的使用

这是一个从原始的sim_data插件分叉并修改的版本,增加了对Android 11、12及更高版本的支持。这个Flutter插件用于检索SIM卡数据,支持双卡,目前仅适用于Android。

安装

在您的pubspec.yaml文件中添加sim_data_plus作为依赖项。

确保您的AndroidManifest.xml文件包含以下权限:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

使用

在使用此插件之前,必须确保用户已授权访问其电话,例如使用permission_handler插件。

然后您可以使用该插件:

import 'package:sim_data_plus/sim_data.dart';

void printSimCardsData() async {
  try {
    // 获取SIM卡数据
    SimData simData = await SimDataPlugin.getSimData();
    for (var s in simData.cards) {
      // 打印每个SIM卡的序列号
      print('Serial number: ${s.serialNumber}');
    }
  } on PlatformException catch (e) {
    // 捕获异常并打印错误信息
    debugPrint("error! code: ${e.code} - message: ${e.message}");
  }
}

void main() => printSimCardsData();

下面是一个完整的示例demo,展示了如何使用sim_data_plus插件来获取和显示SIM卡数据:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sim_data_plus/sim_data.dart';

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _isLoading = true;
  SimData? _simData;
  String exception = '';

  [@override](/user/override)
  void initState() {
    super.initState();
    init(); // 初始化方法
  }

  Future<void> init() async {
    try {
      // 获取访问电话权限的状态
      var status = await Permission.phone.status;
      if (!status.isGranted) {
        // 如果没有授予权限,则请求权限
        bool isGranted = await Permission.phone.request().isGranted;
        if (!isGranted) return;
      }

      // 调用插件方法获取SIM卡数据
      await SimDataPlugin.getSimData().then((simData){
        setState(() {
          _isLoading = false;
          _simData = simData;
          for (var item in _simData!.cards) {
            if(item.serialNumber == null){
              print("Serial Number is null need to ussd call");
            }
          }
        });
      });

    } catch (e) {
      debugPrint(e.toString());
      setState(() {
        _isLoading = false;
        _simData = null;
        exception = e.toString();
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    var cards = _simData?.cards;
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Sim data demo')), // 标题栏
        body: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(20.0),
              child: Column(
                children: cards != null
                    ? cards.isEmpty
                        ? [const Text('No sim card present')] // 如果没有SIM卡
                        : cards
                            .map(
                              (SimCard card) => ListTile(
                                leading: const Icon(Icons.sim_card), // 图标
                                title: const Text('Card'), // 标题
                                subtitle: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text('carrierName: ${card.carrierName}'),
                                    Text('countryCode: ${card.countryCode}'),
                                    Text('displayName: ${card.displayName}'),
                                    Text('isDataRoaming: ${card.isDataRoaming}'),
                                    Text('isNetworkRoaming: ${card.isNetworkRoaming}'),
                                    Text('phoneNumber: ${card.phoneNumber}'),
                                    Text('serialNumber: ${card.serialNumber}'),
                                    Text('subscriptionId: ${card.subscriptionId}'),
                                    Text('phoneNumber:${card.phoneNumber}'),
                                    Text('slotIndex:${card.slotIndex}'),
                                  ],
                                ),
                              ),
                            )
                            .toList()
                    : [
                        Center(
                          child: _isLoading
                              ? const CircularProgressIndicator() // 加载指示器
                              :  Text(exception), // 显示异常信息
                        )
                      ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

更多关于Flutter获取SIM卡数据插件sim_data_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter获取SIM卡数据插件sim_data_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用Flutter插件sim_data_plus来获取SIM卡数据的示例代码。这个插件允许你访问SIM卡的一些基本信息,比如SIM卡的运营商、国家代码、SIM卡的序列号等。

首先,你需要在你的Flutter项目中添加sim_data_plus插件。打开你的pubspec.yaml文件,并在dependencies部分添加以下行:

dependencies:
  flutter:
    sdk: flutter
  sim_data_plus: ^最新版本号  # 请替换为最新版本号

然后,运行flutter pub get来安装插件。

接下来,在你的Flutter应用中,你可以使用以下代码来获取并显示SIM卡数据:

import 'package:flutter/material.dart';
import 'package:sim_data_plus/sim_data_plus.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SimInfoScreen(),
    );
  }
}

class SimInfoScreen extends StatefulWidget {
  @override
  _SimInfoScreenState createState() => _SimInfoScreenState();
}

class _SimInfoScreenState extends State<SimInfoScreen> {
  String? carrierName;
  String? countryCode;
  String? simSerialNumber;
  String? subscriberId;
  String? integratedCircuitCardIdentifier;
  String? mobileNetworkCode;
  String? mobileCountryCode;
  String? serviceProviderName;
  String? numericName;
  String? isoCountry;

  @override
  void initState() {
    super.initState();
    _getSimInfo();
  }

  Future<void> _getSimInfo() async {
    try {
      SimData? simData = await SimDataPlus.simData;
      
      if (simData != null) {
        setState(() {
          carrierName = simData.carrierName;
          countryCode = simData.countryCode.toString();
          simSerialNumber = simData.simSerialNumber;
          subscriberId = simData.subscriberId;
          integratedCircuitCardIdentifier = simData.integratedCircuitCardIdentifier;
          mobileNetworkCode = simData.mobileNetworkCode.toString();
          mobileCountryCode = simData.mobileCountryCode.toString();
          serviceProviderName = simData.serviceProviderName;
          numericName = simData.numericName;
          isoCountry = simData.isoCountry;
        });
      } else {
        // 处理无SIM卡的情况
        setState(() {
          carrierName = "No SIM Card";
          countryCode = "";
          simSerialNumber = "";
          subscriberId = "";
          integratedCircuitCardIdentifier = "";
          mobileNetworkCode = "";
          mobileCountryCode = "";
          serviceProviderName = "";
          numericName = "";
          isoCountry = "";
        });
      }
    } catch (e) {
      print("Error getting SIM info: $e");
      // 错误处理
      setState(() {
        carrierName = "Error";
        countryCode = "";
        simSerialNumber = "";
        subscriberId = "";
        integratedCircuitCardIdentifier = "";
        mobileNetworkCode = "";
        mobileCountryCode = "";
        serviceProviderName = "";
        numericName = "";
        isoCountry = "";
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SIM Card Info'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Carrier Name: $carrierName'),
            Text('Country Code: $countryCode'),
            Text('SIM Serial Number: $simSerialNumber'),
            Text('Subscriber ID: $subscriberId'),
            Text('ICCID: $integratedCircuitCardIdentifier'),
            Text('MNC: $mobileNetworkCode'),
            Text('MCC: $mobileCountryCode'),
            Text('Service Provider Name: $serviceProviderName'),
            Text('Numeric Name: $numericName'),
            Text('ISO Country: $isoCountry'),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,该应用使用sim_data_plus插件来获取SIM卡信息,并在UI中显示这些信息。请注意,由于访问SIM卡信息涉及到用户的隐私,因此在某些操作系统和设备上可能需要额外的权限。确保你的应用已经正确请求并获得了必要的权限。

回到顶部