使用wifi_iot写一个flutter弹出WIFI选择连接的页面,并返回给调用页面的完整demo.
时间: 2024-02-25 11:59:22 浏览: 496
好的,以下是一个使用wifi_iot插件编写的Flutter页面,用于弹出WIFI选择连接的页面,并返回所选网络的完整demo:
1. 首先,您需要在Flutter项目中添加wifi_iot插件。在pubspec.yaml文件中添加以下依赖项:
```yaml
dependencies:
wifi_iot: ^0.4.0
```
2. 创建一个新的Flutter页面,并在该页面中引入wifi_iot插件:
```dart
import 'package:flutter/material.dart';
import 'package:wifi_iot/wifi_iot.dart';
```
3. 在该页面的状态类中添加一个名为“_showWifiList”的方法,该方法将弹出一个对话框,显示可用的WiFi网络列表,并且当用户选择一个网络时,将调用名为“_connectToWifi”的方法连接到该网络:
```dart
class _MyHomePageState extends State<MyHomePage> {
String _ssid = "";
String _password = "";
// 弹出WIFI列表对话框
Future<void> _showWifiList() async {
List<WifiNetwork> list = await WifiIot.getWifiList();
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("选择一个网络"),
content: Container(
width: double.maxFinite,
child: ListView.builder(
shrinkWrap: true,
itemCount: list.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(list[index].ssid),
onTap: () {
Navigator.pop(context);
setState(() {
_ssid = list[index].ssid;
});
_connectToWifi();
},
);
},
),
),
);
},
);
}
// 连接到所选的网络
Future<void> _connectToWifi() async {
bool isConnected = await WifiIot.connect(_ssid);
setState(() {
_password = "";
});
if (isConnected) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("已连接到 $_ssid"),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("连接失败,请重试"),
),
);
}
}
// 页面主体
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("WiFi连接"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'当前连接的网络:',
),
Text(
'$_ssid',
style: Theme.of(context).textTheme.headline4,
),
SizedBox(
height: 20,
),
ElevatedButton(
onPressed: _showWifiList,
child: Text("选择网络"),
),
],
),
),
);
}
}
```
4. 最后,在Flutter应用程序的入口点中,将该页面作为默认页面:
```dart
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'WiFi连接',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
```
这样,当用户单击“选择网络”按钮时,将弹出一个对话框,其中包含可用的WiFi网络列表。当用户选择一个网络时,将连接到该网络,并在页面上显示所选网络的名称。
阅读全文
相关推荐


















