0

我检查了手机是否连接到互联网。我用过这种方式。它工作得很好。但我每节课都用这种方式。相同的代码重复。我不明白,如何在全球使用这种代码。

初始化变量

bool isOffline = false;

初始化状态

  @override
  void initState() {
    ConnectionStatusSingleton connectionStatus =
        ConnectionStatusSingleton.getInstance();// connectionStatusSingleton is another class
    _connectionChangeStream =
        connectionStatus.connectionChange.listen(connectionChanged);
    connectionChanged(connectionStatus.hasConnection);
    super.initState();
  }

connectionChanged 方法

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,
4

1 回答 1

1

您可以使用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/connectivityhttps://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();
  ...
)
...

编辑:我已经用实际工作的东西改进了代码示例。

于 2019-06-05T06:38:18.927 回答