Connect a wifi network with flutter

58 Views Asked by At

I want to connect a specify selected WiFi in Flutter. I used https://pub.dev/packages/wifi_scan and https://pub.dev/packages/wifi_iot. The WiFi Scan worked (the main idea is tap on a 'x' WiFi and connect it), however WiFi_iot doesn't work.

1

There are 1 best solutions below

1
AudioBubble On

Use this code for connecting to a specific WiFi network and implement on your wifi list onTap.

// Replace with actual implementation based on the wifi plugin

import 'package:wifi/wifi.dart' as wifi;

// ... existing code ...

Future<void> _connectToWiFi(WiFiAccessPoint network) async {
  if (Theme.of(context).platform == TargetPlatform.android) {
    final connectivityResult = await (connectivity.Connectivity().checkConnectivity());

if (connectivityResult != connectivity.ConnectivityResult.none) {
  final wifiState = await wifi.Wifi.getWifiState();
  if (wifiState == wifi.WifiState.wifiEnabled) {
    final result = await wifi.Wifi.connect(network.ssid, password: network.password);
    if (result == wifi.Result.success) {
      print('Connected to WiFi network (Android): ${network.ssid}');
    } else {
      print('Connection failed (Android): ${result.toString()}');
    }
  } else {
    print('WiFi is disabled (Android)');
   }
  } else {
    print('No internet connection available (Android)');
  }
 }
  // ... existing code ...
}
  1. Make sure to request the necessary permissions (LOCATION for Android WiFi scanning) in your Manifest.xml file.
  2. Refer to the documentation of the chosen platform-specific connection plugin (connectivity/wifi for Android, flutter_回し for iOS) for detailed usage instructions.
  3. Handle potential errors and edge cases during the connection process, providing informative messages to the user.

By combining wifi_scan for network discovery and platform-specific methods for connection, you can create a robust WiFi connection experience in your Flutter app.