当您启动应用程序时,中心的铭文 Hello World!。单击“检查”按钮后,理论上应该会出现一条关于 Internet 连接或不存在的消息。什么都没发生。为什么?下面是完整的代码和截图。
主要.dart
import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';
import 'dart:async';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Name App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Name Page'),
),
body: MyHomePage(),
),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _str = 'Hello World!';
@override
void initState() {
super.initState();
}
@override
void dispose() {
super.dispose();
}
void _f1() {
setState(() {
});
}
Future<void> _funCheckInternetConnection() async {
ConnectivityResult result = await Connectivity().checkConnectivity();
if(result == ConnectivityResult.mobile) {
setState(() {
_str = 'connected to a mobile network';
});
} else if(result == ConnectivityResult.wifi) {
setState(() {
_str = 'connected to a wifi network';
});
} else if(result == ConnectivityResult.none) {
setState(() {
_str = 'disconnected to a network';
});
}
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
Align(
alignment: Alignment.topCenter,
child: TextButton(
onPressed: () { _funCheckInternetConnection(); },
child: Container(
width: 100.0,
height: 50.0,
decoration: BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.all(
Radius.circular(10.0)
)
),
alignment: Alignment.center,
child: Text(
'Check',
style: TextStyle(
fontSize: 20,
color: Colors.deepPurpleAccent
),
),
),
),
),
Align(
alignment: Alignment.center,
child: Text(
_str,
style: TextStyle(
fontSize: 26.0,
color: Colors.pink
),
),
),
],
);
}
}

为了得到想要的结果,我们只需要添加
await,因为该方法_funCheckInternetConnection是异步的: