有了这个Connectivity Plugin的帮助,我能够得到连接状态,即移动的网络,wifi或没有使用以下代码:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:connectivity/connectivity.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _connectionStatus = 'Unknown';
final Connectivity _connectivity = new Connectivity();
StreamSubscription<ConnectivityResult> _connectivitySubscription;
@override
void initState() {
super.initState();
initConnectivity();
_connectivitySubscription =
_connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
setState(() => _connectionStatus = result.toString());
});
}
@override
void dispose() {
_connectivitySubscription.cancel();
super.dispose();
}
Future<Null> initConnectivity() async {
String connectionStatus;
try {
connectionStatus = (await _connectivity.checkConnectivity()).toString();
} on PlatformException catch (e) {
print(e.toString());
connectionStatus = 'Failed to get connectivity.';
}
if (!mounted) {
return;
}
setState(() {
_connectionStatus = connectionStatus;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: const Text('Plugin example app'),
),
body: new Center(
child: new Text('Connection Status: $_connectionStatus\n')),
);
}
}
现在我想要的是,当手机连接到wifi时,得到Wifi的名称。详细说明:假设用户已经将他/她的手机与名为“家庭WiFi”的WiFi连接,从我写的代码中,我只能得到手机是否连接到WiFi,我还想得到手机是否连接到WiFi的WiFi名称,即“家庭WiFi”.
3条答案
按热度按时间kcrjzv8t1#
它只是调用getWifiName(),在network_info_plus插件中可用。这个方法以前在connectivity插件中可用,但后来被移到了这个新插件中。
在iOS中,使用此解决方案需要步骤described in this answer。
pb3skfrl2#
在2022年,我已经切换到network_info_plus库,在我的情况下,这个新版本比旧版本更好。而且它仍然使用与旧版本相同的方法名称来获得wifi的名称:
getWifiName()
.fzwojiic3#
使用network_info_plus包。
将此代码添加到android manifest: