Flutter无线网络管理插件android_flutter_wifi的使用

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

Flutter无线网络管理插件android_flutter_wifi的使用

android_flutter_wifi 是一个用于Flutter应用程序的Android Wi-Fi插件,允许开发者获取可用的Wi-Fi接入点列表,并执行其他与Wi-Fi相关的操作。该插件仅适用于Android平台,因为Apple不允许开发者直接操作Wi-Fi。

1. 开始使用

1.1 添加权限

AndroidManifest.xml 文件中添加以下权限:

<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-feature android:name="android.hardware.wifi" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
1.2 添加依赖

pubspec.yaml 文件中添加 permission_handler 依赖:

dependencies:
  permission_handler: ^9.2.0
  android_flutter_wifi: ^latest_version

2. 初始化插件

在使用插件之前,需要初始化并请求位置权限。init() 方法返回一个布尔值,表示权限是否已授予。

import 'package:android_flutter_wifi/android_flutter_wifi.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

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

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

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

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
  }

  Future<void> initPlatformState() async {
    // 请求位置权限
    var status = await Permission.location.request();
    if (status.isGranted) {
      // 初始化插件
      await AndroidFlutterWifi.init();
      setState(() {
        _platformVersion = "Permission Granted";
      });
    } else {
      setState(() {
        _platformVersion = "Permission Denied";
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Wi-Fi Management Example'),
        ),
        body: Center(
          child: Text('Running on: $_platformVersion\n'),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            getWifiList();
          },
          child: const Icon(Icons.wifi),
        ),
      ),
    );
  }

  /// 获取Wi-Fi列表
  void getWifiList() async {
    List<WifiNetwork> wifiList = await AndroidFlutterWifi.getWifiScanResult();
    if (wifiList.isNotEmpty) {
      WifiNetwork wifiNetwork = wifiList[0];
      print('Name: ${wifiNetwork.ssid}');
      print('Signal Level: ${wifiNetwork.level}');
    } else {
      print('No Wi-Fi networks found');
    }
  }
}

3. 常用功能

3.1 获取Wi-Fi接入点列表

通过 getWifiScanResult() 方法可以获取当前可用的Wi-Fi接入点列表。每个 WifiNetwork 对象包含有关接入点的详细信息,例如SSID、信号强度等。

void getWifiList() async {
  List<WifiNetwork> wifiList = await AndroidFlutterWifi.getWifiScanResult();
  if (wifiList.isNotEmpty) {
    for (var network in wifiList) {
      print('SSID: ${network.ssid}, Signal Level: ${network.level}');
    }
  } else {
    print('No Wi-Fi networks found');
  }
}
3.2 检查连接速度

isConnectionFast() 方法可以检查当前Wi-Fi连接是否为快速连接。

void checkConnectionSpeed() {
  bool isFast = AndroidFlutterWifi.isConnectionFast();
  print('Is connection fast: $isFast');
}
3.3 获取连接类型

getConnectionType() 方法可以获取当前设备的连接类型(Wi-Fi 或蜂窝网络)。

void getConnectionType() {
  String type = AndroidFlutterWifi.getConnectionType();
  print('Connection type: $type');
}
3.4 获取当前Wi-Fi连接信息

getActiveWifiInfo() 方法可以获取当前设备连接的Wi-Fi网络的详细信息,包括IP地址、MAC地址等。

void getActiveWifiNetwork() async {
  ActiveWifiNetwork activeWifiNetwork = await AndroidFlutterWifi.getActiveWifiInfo();
  print('SSID: ${activeWifiNetwork.ssid}');
  print('IP Address: ${activeWifiNetwork.ipAddress}');
  print('MAC Address: ${activeWifiNetwork.macAddress}');
}
3.5 获取DHCP信息

getDhcpInfo() 方法可以获取当前Wi-Fi网络的DHCP信息,例如网关地址。

void getDhcpInfo() async {
  DhcpInfo dhcpInfo = await AndroidFlutterWifi.getDhcpInfo();
  String gatewayIp = AndroidFlutterWifi.toIp(dhcpInfo.gateway!);
  String formedIp = AndroidFlutterWifi.getFormedIp(gatewayIp);
  print('Gateway: $gatewayIp');
  print('Formed IP: $formedIp');
}
3.6 连接到指定的Wi-Fi网络

connectToNetwork() 方法可以连接到指定的Wi-Fi网络,需要提供SSID和密码。

void connectToNetwork() async {
  String ssid = 'Your_SSID';
  String password = 'Your_Password';
  
  if (ssid.isEmpty || password.isEmpty) {
    throw ("SSID and Password can't be empty");
  }

  bool result = await AndroidFlutterWifi.connectToNetwork(ssid, password);
  print('Connection result: $result');
}
3.7 获取所有已保存的Wi-Fi网络

getConfiguredNetworks() 方法可以获取设备上所有已保存的Wi-Fi网络。

void getConfiguredNetworks() async {
  List<ConfiguredNetwork> list = await AndroidFlutterWifi.getConfiguredNetworks();
  for (var network in list) {
    print('Network ID: ${network.networkId}');
  }
}
3.8 忘记指定的Wi-Fi网络

forgetWifiWithSSID() 方法可以通过提供SSID来忘记指定的Wi-Fi网络。

void forgetWifi() async {
  ActiveWifiNetwork activeWifiNetwork = await AndroidFlutterWifi.getActiveWifiInfo();
  bool result = await AndroidFlutterWifi.forgetWifiWithSSID(activeWifiNetwork.ssid!);
  print('Forget Wi-Fi result: $result');
}
3.9 连接到预配置的Wi-Fi网络

connectToNetworkWithSSID() 方法可以连接到预配置的Wi-Fi网络,只需提供SSID即可。

void connectToPreconfiguredNetwork() async {
  bool result = await AndroidFlutterWifi.connectToNetworkWithSSID('Your_SSID');
  print('Connection result: $result');
}

4. 其他功能

  • 启用/禁用Wi-Fi:可以使用 enableWifi()disableWifi() 方法来启用或禁用设备的Wi-Fi。
  • 检查Wi-Fi是否已启用:使用 isWifiEnabled() 方法可以检查设备的Wi-Fi是否已启用。
void enableOrDisableWifi(bool enable) async {
  if (enable) {
    await AndroidFlutterWifi.enableWifi();
  } else {
    await AndroidFlutterWifi.disableWifi();
  }
}

void checkWifiStatus() async {
  bool isEnabled = await AndroidFlutterWifi.isWifiEnabled();
  print('Wi-Fi is enabled: $isEnabled');
}

5. 注意事项

  • 如果您的IP地址格式不正确或反转,可以使用 getFormedIp() 方法来获取格式正确的IP地址。
  • 该插件要求在Android 9.0及以上版本中启用位置权限,以自动启用Wi-Fi。请确保已启用GPS。

6. 完整示例代码

以下是一个完整的示例代码,展示了如何使用 android_flutter_wifi 插件来管理Wi-Fi连接:

import 'package:android_flutter_wifi/android_flutter_wifi.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

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

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

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

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
  }

  Future<void> initPlatformState() async {
    // 请求位置权限
    var status = await Permission.location.request();
    if (status.isGranted) {
      // 初始化插件
      await AndroidFlutterWifi.init();
      setState(() {
        _platformVersion = "Permission Granted";
      });
    } else {
      setState(() {
        _platformVersion = "Permission Denied";
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Wi-Fi Management Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('Running on: $_platformVersion\n'),
              ElevatedButton(
                onPressed: getWifiList,
                child: const Text('Get Wi-Fi List'),
              ),
              ElevatedButton(
                onPressed: checkConnectionSpeed,
                child: const Text('Check Connection Speed'),
              ),
              ElevatedButton(
                onPressed: getConnectionType,
                child: const Text('Get Connection Type'),
              ),
              ElevatedButton(
                onPressed: getActiveWifiNetwork,
                child: const Text('Get Active Wi-Fi Info'),
              ),
              ElevatedButton(
                onPressed: getDhcpInfo,
                child: const Text('Get DHCP Info'),
              ),
              ElevatedButton(
                onPressed: connectToNetwork,
                child: const Text('Connect to Wi-Fi'),
              ),
              ElevatedButton(
                onPressed: getConfiguredNetworks,
                child: const Text('Get Saved Networks'),
              ),
              ElevatedButton(
                onPressed: forgetWifi,
                child: const Text('Forget Wi-Fi'),
              ),
              ElevatedButton(
                onPressed: connectToPreconfiguredNetwork,
                child: const Text('Connect to Pre-configured Network'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 获取Wi-Fi列表
  void getWifiList() async {
    List<WifiNetwork> wifiList = await AndroidFlutterWifi.getWifiScanResult();
    if (wifiList.isNotEmpty) {
      for (var network in wifiList) {
        print('SSID: ${network.ssid}, Signal Level: ${network.level}');
      }
    } else {
      print('No Wi-Fi networks found');
    }
  }

  /// 检查连接速度
  void checkConnectionSpeed() {
    bool isFast = AndroidFlutterWifi.isConnectionFast();
    print('Is connection fast: $isFast');
  }

  /// 获取连接类型
  void getConnectionType() {
    String type = AndroidFlutterWifi.getConnectionType();
    print('Connection type: $type');
  }

  /// 获取当前Wi-Fi连接信息
  void getActiveWifiNetwork() async {
    ActiveWifiNetwork activeWifiNetwork = await AndroidFlutterWifi.getActiveWifiInfo();
    print('SSID: ${activeWifiNetwork.ssid}');
    print('IP Address: ${activeWifiNetwork.ipAddress}');
    print('MAC Address: ${activeWifiNetwork.macAddress}');
  }

  /// 获取DHCP信息
  void getDhcpInfo() async {
    DhcpInfo dhcpInfo = await AndroidFlutterWifi.getDhcpInfo();
    String gatewayIp = AndroidFlutterWifi.toIp(dhcpInfo.gateway!);
    String formedIp = AndroidFlutterWifi.getFormedIp(gatewayIp);
    print('Gateway: $gatewayIp');
    print('Formed IP: $formedIp');
  }

  /// 连接到指定的Wi-Fi网络
  void connectToNetwork() async {
    String ssid = 'Your_SSID';
    String password = 'Your_Password';
    
    if (ssid.isEmpty || password.isEmpty) {
      throw ("SSID and Password can't be empty");
    }

    bool result = await AndroidFlutterWifi.connectToNetwork(ssid, password);
    print('Connection result: $result');
  }

  /// 获取所有已保存的Wi-Fi网络
  void getConfiguredNetworks() async {
    List<ConfiguredNetwork> list = await AndroidFlutterWifi.getConfiguredNetworks();
    for (var network in list) {
      print('Network ID: ${network.networkId}');
    }
  }

  /// 忘记指定的Wi-Fi网络
  void forgetWifi() async {
    ActiveWifiNetwork activeWifiNetwork = await AndroidFlutterWifi.getActiveWifiInfo();
    bool result = await AndroidFlutterWifi.forgetWifiWithSSID(activeWifiNetwork.ssid!);
    print('Forget Wi-Fi result: $result');
  }

  /// 连接到预配置的Wi-Fi网络
  void connectToPreconfiguredNetwork() async {
    bool result = await AndroidFlutterWifi.connectToNetworkWithSSID('Your_SSID');
    print('Connection result: $result');
  }
}

更多关于Flutter无线网络管理插件android_flutter_wifi的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter无线网络管理插件android_flutter_wifi的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,android_flutter_wifi 是一个用于 Flutter 的插件,它允许你在 Android 设备上管理无线网络连接。以下是一个基本的使用示例,展示如何通过 Flutter 代码来使用这个插件。

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

dependencies:
  flutter:
    sdk: flutter
  android_flutter_wifi: ^x.y.z  # 请替换为最新版本号

然后,运行 flutter pub get 来获取插件。

接下来,你需要对 Android 项目进行一些配置,以便插件能够正常工作。在 android/app/src/main/AndroidManifest.xml 文件中,添加以下权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

由于 ACCESS_FINE_LOCATIONACCESS_COARSE_LOCATION 权限在 Android 6.0(API 级别 23)及以上版本中需要在运行时请求,你还需要在 Dart 代码中处理这些权限请求。

以下是一个完整的 Flutter 代码示例,展示如何使用 android_flutter_wifi 插件来扫描 WiFi 网络并连接到指定的网络:

import 'package:flutter/material.dart';
import 'package:android_flutter_wifi/android_flutter_wifi.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> {
  List<WifiScanResult> wifiList = [];
  bool isScanning = false;
  bool isConnecting = false;

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

  Future<void> _requestPermissions() async {
    Map<Permission, PermissionStatus> statuses = await Permission.requestMultiple([
      Permission.accessFineLocation,
      Permission.accessWifiState,
      Permission.changeWifiState,
      Permission.changeNetworkState,
    ]);

    if (statuses[Permission.accessFineLocation]?.isGranted == true &&
        statuses[Permission.accessWifiState]?.isGranted == true &&
        statuses[Permission.changeWifiState]?.isGranted == true &&
        statuses[Permission.changeNetworkState]?.isGranted == true) {
      // Permissions granted, proceed with scanning
    } else {
      // Handle permission denial
    }
  }

  Future<void> scanWifi() async {
    setState(() {
      isScanning = true;
    });

    try {
      wifiList = await Wifi.scanResults();
    } catch (e) {
      print("Error scanning WiFi: $e");
    } finally {
      setState(() {
        isScanning = false;
      });
    }
  }

  Future<void> connectToWifi(String ssid, String password) async {
    setState(() {
      isConnecting = true;
    });

    try {
      bool success = await Wifi.connect(ssid, password);
      if (success) {
        print("Connected to $ssid");
      } else {
        print("Failed to connect to $ssid");
      }
    } catch (e) {
      print("Error connecting to WiFi: $e");
    } finally {
      setState(() {
        isConnecting = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('WiFi Manager'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: <Widget>[
              Button(
                child: Text('Scan WiFi'),
                onPressed: () {
                  if (!isScanning) {
                    scanWifi();
                  }
                },
              ),
              SizedBox(height: 16),
              Expanded(
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: wifiList.length,
                  itemBuilder: (context, index) {
                    WifiScanResult wifi = wifiList[index];
                    return ListTile(
                      title: Text(wifi.ssid),
                      subtitle: Text("${wifi.bssid} - ${wifi.level} dB"),
                      trailing: IconButton(
                        icon: Icon(Icons.connect_without_protection),
                        onPressed: () {
                          // Replace with your actual password
                          String password = "your_password_here";
                          connectToWifi(wifi.ssid, password);
                        },
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

请注意:

  1. 代码中使用了 permission_handler 插件来处理运行时权限请求。你需要将其添加到 pubspec.yaml 文件中并运行 flutter pub get
  2. 替换 your_password_here 为你要连接 WiFi 网络的实际密码。
  3. 插件的某些功能可能依赖于设备的 Android 版本和制造商的定制,因此在实际应用中,请确保在多个设备上进行测试。

这个示例展示了如何使用 android_flutter_wifi 插件来扫描 WiFi 网络并连接到指定的网络。根据你的具体需求,你可以进一步扩展和修改这个示例。

回到顶部