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

时间:2019-06-05 04:49:50

标签: flutter dart flutter-dependencies flutter-navigation

我检查了手机是否已连接到互联网。我用这种方式。运行良好。但是我在每个班级都使用这种方式。相同的代码重复。我不明白,如何在全局范围内使用这种代码。

初始化变量

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,

1 个答案:

答案 0 :(得分: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();
  ...
)
...

编辑:我对代码示例进行了改进,使其具有实际可用的功能。