如何在全球范围内使用这种方法?

How to use this kind of method in global?

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

初始化变量

bool isOffline = false;

initState

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

您可以使用 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 and https://pub.dev/packages/data_connection_checker

要重复使用 AppBar 小部件,您可以将其提取到自己的 class:

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();
  ...
)
...

编辑:我用实际可行的东西改进了代码示例。