我检查了手机是否连接到互联网。我是这样用的。它运作良好。但是我每节课都用这种方式。重复相同的代码。我不明白,如何在全局中使用这种代码。
初始化变量
bool isOffline = false;
初始化状态
@override
void initState() {
ConnectionStatusSingleton connectionStatus =
ConnectionStatusSingleton.getInstance();// connectionStatusSingleton is another class
_connectionChangeStream =
connectionStatus.connectionChange.listen(connectionChanged);
connectionChanged(connectionStatus.hasConnection);
super.initState();
}
连接更改方法
void connectionChanged(dynamic hasConnection) {
setState(() {
isOffline = !hasConnection;
});
}
之后我在小部件中使用 如果连接不可用我显示appBar,
appBar: isOffline
? PreferredSize(
preferredSize: Size.fromHeight(20.0),
child: AppBar(
leading: Container(),
centerTitle: true,
backgroundColor: Colors.red,
title: Text(
AppTranslations.of(context).text("connection_drop"),
style: TextStyle(fontSize: 15.0, color: Colors.white),
),
),
)
: null,
您可以使用它StreamBuilder
来实现这一点。只需将依赖于此的小部件包装Stream
起来即可。
像这样的东西:
void main() {
runApp(App());
}
class App extends StatelessWidget {
const App({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: StreamBuilder<ConnectivityResult>(
stream: Connectivity().onConnectivityChanged,
initialData: ConnectivityResult.none,
builder: (context, snapshot) {
switch (snapshot.data) {
case ConnectivityResult.wifi:
return Text("we're on a wifi network");
case ConnectivityResult.mobile:
return Text("we're on a mobile network");
case ConnectivityResult.none:
return Text('no network connection');
}
},
),
),
),
);
}
}
此外,您可能想查看https://pub.dev/packages/connectivity和https://pub.dev/packages/data_connection_checker
要重用 AppBar 小部件,您可以在其自己的类中提取它:
class MyAppBar extends StatelessWidget {
...
@override
Widget build(BuildContext context) {
return AppBar(
title: StreamBuilder<ConnectivityResult>(
...
),
);
}
...
}
// every time you need it, just pass it as an argument to the `Scaffold`'s `appBar` parameter.
...
Scaffold(
...
appbar: MyAppBar();
...
)
...
编辑:我已经用实际工作的东西改进了代码示例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句