我很难创建一个 StreamProvider。我想在连接离线时显示小吃店。
为此,我创建了一个 StreamProvider,它会在值更改时通知小部件。
但我不知道把我的小部件放在哪里来显示刷新栏(改进的小吃栏)。
我现在有:
我的连接服务:
class ConnectivityService {
ConnectivityService._privateConstructor();
static final ConnectivityService instance =
ConnectivityService._privateConstructor();
StreamController<ConnectionStatus> connectionStatusController =
StreamController<ConnectionStatus>();
ConnectivityService() {
Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult result) async {
bool isDeviceConnected = false;
if (result != ConnectivityResult.none) {
isDeviceConnected = await DataConnectionChecker().hasConnection;
}
connectionStatusController.add(isDeviceConnected == true
? ConnectionStatus.Online
: ConnectionStatus.Offline);
});
}
}
我的notifWidget
import 'dart:js';
import 'package:another_flushbar/flushbar_helper.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:wetip/Services/ConnectivityService.dart';
class NotifWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final connectStatus = Provider.of<ConnectionStatus>(context, listen: false);
if (connectStatus == ConnectionStatus.Offline) {
return Container(
child: FlushbarHelper.createError(message: 'Offline'),
);
}
return context.widget;
}
}
我的 main.dart
我不知道把我的小部件放在哪里。我希望它在应用程序离线时每次在应用程序中显示flushbar(相当于snackbar)
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final Future initFuture = LauncherService.initialize(context);
return StreamProvider<ConnectionStatus>(
create: (context)=>ConnectivityService.instance.connectionStatusController.stream,
initialData: ConnectionStatus.Online,
child:NotifWidget(??? MaterialApp(
title: L.Localize('App'),
theme: MyTheme.defaultTheme,
debugShowCheckedModeBanner: false,
navigatorKey: navigatorKey,
home: FutureBuilder(
future: initFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (Globals.accessTokenManager.isUserLoggedIn) {
} else
return WelcomeOnBoardScreen();
}
return SplashScreen();
}),
));
}
}