Flutter : is it possible to implement a snackbar one time in main.dart for example for all screen when the connectivity status changed - flutter

i make an enum for a connectivity :
enum ConnectivityStatus{
Wifi,
Cellular,
Offline
}
then i create a service to check the Connectivity :
import 'dart:async';
import 'package:Zabatnee/activities_app/enum/connectivity_status.dart';
import 'package:connectivity/connectivity.dart';
class ConnectivityService{
StreamController<ConnectivityStatus> connectionStatusController = StreamController<ConnectivityStatus>();
ConnectivityService(){
Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
var connectionStatus = _getStatusFromResult(result);
connectionStatusController.add(connectionStatus);
});
}
ConnectivityStatus _getStatusFromResult(ConnectivityResult result) {
switch (result) {
case ConnectivityResult.mobile:
return ConnectivityStatus.Cellular;
case ConnectivityResult.wifi:
return ConnectivityStatus.Wifi;
case ConnectivityResult.none:
return ConnectivityStatus.Offline;
default:
return ConnectivityStatus.Offline;
}
}
}
and what i need is to check the connectivity status in all screen that i created. Can I do it once for all screens all, or i must check the connnectivity for each one individually.

You can check the connectivity status once & that will be implemented for all of your app.
You just have to create a wrapper class & subscribe to the Connectivity stream & apply the logic in this wrapper class.
Your whole widget will be wrapped by this widget.
MaterialApp(
..
home: ConnectivityWrapper(
childWidget: YourWidget(), // replace this with your own home widget
),
);
The wrapper widget will look something like this:
class ConnectivityWrapper extends StatefulWidget {
ConnectivityWrapper(this.childWidget);
final Widget childWidget;
#override
_ConnectivityWrapperState createState() => _ConnectivityWrapperState();
}
class _ConnectivityWrapperState extends State<ConnectivityWrapper> {
StreamSubscription<ConnectivityStatus> subscription;
#override
void initState() {
super.initState();
subscription = connectionStatusController.stream.listen((status)
{
if(status == ConnectivityStatus.Offline) {
// Your logic here (Toast message or something else)
}
},
onDone() {
// Your logic here
},
onError: () {
// Your logic here
});
}
#override
Widget build(BuildContext context) {
return widget.childWidget;
}
#override
void dispose() {
// unsubscribe to the stream
subscription.cancel();
super.dispose();
}
}

Related

Cubit - listener does not catching the first state transition

I'm using a Cubit in my app and I'm struggling to understand one behavior.
I have a list of products and when I open the product detail screen I want to have a "blank" screen with a loading indicator until receiving the data to populate the layout, but the loading indicator is not being triggered in the listener (only in this first call, when making a refresh in the screen it shows the loader).
I'm using a BlocConsumer and i'm making the request in the builder when catching the ApplicationInitialState (first state), in cubit I'm emitting the ApplicationLoadingState(), but this state transition is not being caught in the listener, only when the SuccessState is emitted the listener triggers and tries to remove the loader.
I know the listener does not catch the first State emitted but I was expecting it to catch the first state transition.
UI
#override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
#override
Widget build(BuildContext context) {
_l10n = AppLocalizations.of(context);
return _buildConsumer();
}
_buildConsumer() {
return BlocConsumer<ProductCubit, ApplicationState>(
bloc: _productCubit,
builder: (context, state) {
if (state is ApplicationInitialState) {
_getProductDetail();
}
return Scaffold(
appBar: _buildAppbar(state),
body: _buildBodyState(state),
);
},
listener: (previous, current) async {
if (current is ApplicationLoadingState) {
_loadingIndicator.show(context);
} else {
_loadingIndicator.close(context);
}
},
);
}
Cubit
class ProductCubit extends Cubit<ApplicationState> with ErrorHandler {
final ProductUseCase _useCase;
ProductCubit({
required ProductUseCase useCase,
}) : _useCase = useCase,
super(const ApplicationInitialState());
void getProductDetail(String id) async {
try {
emit(const ApplicationLoadingState());
final Product = await _useCase.getProductDetail(id);
emit(CSDetailSuccessState(
detail: ProductDetailMapper.getDetail(Product),
));
} catch (exception) {
emit(getErrorState(exception));
}
}
}
ApplicationLoadingState
abstract class ApplicationState extends Equatable {
const ApplicationState();
#override
List<Object> get props => [];
}
class ApplicationLoadingState extends ApplicationState {
const ApplicationLoadingState();
}

Calling async event in flutter_bloc

I am trying to fetch data from API as soon as the flutter app loads but I am unable to achieve so
class MarketBloc extends Bloc<MarketListEvent, MarketListState> {
MarketBloc() : super(MarketLoading()) {
on<MarketSelectEvent>((event, emit) async {
emit(MarketLoading());
final data = await ApiCall().getData(event.value!);
globalData = data;
emit(MarketDataFetched(marDat: globalData.data, dealType: event.value));
});
}
}
I have called MarketLoading state as the initial state and I want to call MarketSelectEvent just after that but in the current code, action is required to do so and i want to achieve it without any action.
You have 2 options:
add an event from the UI as soon you instantiate the MarketBloc
MarketBloc()..add(MarketSelectEvent())
add an event in the initialization code
MarketBloc() : super(MarketLoading()) {
add(MarketSelectEvent());
}
You could do this with in the initState of whatever the first page is that your app loads.
class TestPage extends StatefulWidget {
#override
State<TestPage> createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
late MarketBloc marketBloc;
#override
void initState() {
super.initState();
marketBloc = BlocProvider.of<MarketBloc>(context);
marketBloc.add(MarketSelectEvent());
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: BlocBuilder<MarketBloc, MarketListState>(
builder: (context, state) {
if (state is MarketLoading) {
return Text('loading...');
}
if (state is MarketDataFetched) {
return ...your UI that contains data from API call
}
},
),
),
);
}
}

How do I integrate flutter_bloc with method channels?

I've started using flutter_bloc package instead of redux to try it out, but I'm not entirely sure how I'm going to call flutter bloc events when receiving things from native (Android/iOS). It was easier with redux because in my parent MyApp widget of my main.dart file, I passed in the redux store to a custom class I created, and dispatched methods from the said class (called MethodChannelHandler).
main.dart:
void main() {
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final Store<AppState> store = Store<AppState>(
// ... redux stuff ...
);
#override
void initState() {
// sauce
MethodChannelHandler(store);
super.initState();
}
}
methodChannelHandler.dart:
class MethodChannelHandler {
Store<AppState> store;
MethodChannelHandler(this.store) {
methodChannel.setMethodCallHandler(_handleMethod);
}
// Handle method calls from native
Future _handleMethod(MethodCall call) async {
if (call.method == A_METHOD) {
store.dispatch("something from native")
}
}
}
NOTE: I'm inept when it comes to programming vocabulary so please, if possible, please give me a small snippet of example code like I have or link me to some GitHub repo I can refer to instead of giving me a block of text I'm probably not going to understand.
In very simple way it's look like this:
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return BlocProvider<SomeBloc>(
create: (_) {
final bloc = SomeBloc(); //Create bloc
MethodChannelHandler(bloc); //Add method handler
return bloc;
},
lazy: false,
child: Text("Content"),
);
}
}
class SomeBloc extends Bloc {
SomeBloc() : super(SomeInitState());
#override
Stream mapEventToState(event) async* {
if (event is SomeEvent) {
//Handle SomeEvent
}
}
}
class MethodChannelHandler {
final SomeBloc someBloc;
MethodChannelHandler(this.someBloc) {
methodChannel.setMethodCallHandler(_handleMethod);
}
// Handle method calls from native
Future _handleMethod(MethodCall call) async {
if (call.method == A_METHOD) {
someBloc.add(SomeEvent("something from native"));
}
}
}

"Multiple widgets used the same GlobalKey" error in flutter

I'm getting an error like the one in the picture. I'm confused because I'm not setting up GlobalKey on every page. I just made a GlobalKey on main.dart for this:
class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
StreamController<bool> _showLockScreenStream = StreamController();
StreamSubscription _showLockScreenSubs;
GlobalKey<NavigatorState> _navigatorKey = GlobalKey();
#override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_showLockScreenSubs = _showLockScreenStream.stream.listen((bool show){
if (mounted && show) {
_showLockScreenDialog();
}
});
}
#override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_showLockScreenSubs?.cancel();
super.dispose();
}
// Listen for when the app enter in background or foreground state.
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
// user returned to our app, we push an event to the stream
_showLockScreenStream.add(true);
} else if (state == AppLifecycleState.inactive) {
// app is inactive
} else if (state == AppLifecycleState.paused) {
// user is about quit our app temporally
} else if (state == AppLifecycleState.suspending) {
// app suspended (not used in iOS)
}
}
#override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: _navigatorKey,
...
);
}
void _showLockScreenDialog() {
_navigatorKey.currentState.
.pushReplacement(new MaterialPageRoute(builder: (BuildContext context) {
return PassCodeScreen();
}));
}
}
I've tried to remove the GlobalKey _navigatorKey but the error still appears.
The error appears when switching pages. Is there anyone who can help me?
There are many kinds of Keys. But the GlobalKey allows access to the state of a widget (if it's a StatefulWigdet).
Then, if you use the same GlobalKey for many of them, there is a conflict with their States.
In addition, they must be of the same type due to its specification:
abstract class GlobalKey<T extends State<StatefulWidget>> extends Key {
// ...
void _register(Element element) {
assert(() {
if (_registry.containsKey(this)) {
assert(element.widget != null);
final Element oldElement = _registry[this]!;
assert(oldElement.widget != null);
assert(element.widget.runtimeType != oldElement.widget.runtimeType);
_debugIllFatedElements.add(oldElement);
}
return true;
}());
_registry[this] = element;
}
// ...
}
This fragment of code shows that in debug mode, there is an assertion for ensuring that there isn't any other GlobalState of the same type previously registered.

how to implement in app time out session in flutter

I want to log a user out after a specific amount time the user has not interacted with the app.
I've wrapped the whole child widget in GestureDetector().
Please suggest if this is the best optimised way of doing this.
class MyWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new GestureDetector(
onTap: () {
// duration reset's to a specific time
startTimeout([int milliseconds]) { return new Timer(duration, handleTimeout); }
},
child: new HomeWidget(),);
}
void handleTimeOut {
// Log User Out
}
}
You should cancel previous timers before initializing a new one
static Timer _sessionTimer;
#override
Widget build(BuildContext context) {
...
onTap: () {
_sessionTimer?.cancel();
// duration reset's to a specific time
_sessionTimer = new Timer(duration, handleTimeout);
},
If you need something for the web target then better setup a key-up and a mouse-click listener on your index.html's 'body' as follows.
...
<body id = 'myapp-main-content'>
...
Then implement the listeners, here is an example borrowed from Task Tracker (https://github.com/botorabi/TaskTracker/tree/master/src/flutter-app/TaskTracker/lib).
import 'dart:async';
import 'dart:html';
import 'package:TaskTracker/service/authstatus.dart';
import 'package:flutter/material.dart';
import 'config.dart';
import 'navigation.links.dart';
import 'service/service.login.dart';
/// Logout user after long inactivity period.
class SessionTimeoutHandler {
static const MAIN_CONTAINER_ID = 'myapp-main-content';
final GlobalKey<NavigatorState> _navigator;
Timer _sessionTimer;
int _timeoutInSeconds;
static DateTime _timeLeft;
SessionTimeoutHandler(this._navigator, this._timeoutInSeconds);
void installLogoutHandler() {
var body = document.getElementById(MAIN_CONTAINER_ID);
body.addEventListener("click", (event) => resetLogoutTimer());
body.addEventListener("keyup", (event) => resetLogoutTimer());
resetLogoutTimer();
}
/// Return the time left to logout in seconds.
/// If user is not authenticated then 0 is returned.
static int timeLeftInSeconds() {
if ((_timeLeft == null) || !Config.authStatus.authenticated) {
return 0;
}
return ((DateTime.now().millisecondsSinceEpoch - _timeLeft.millisecondsSinceEpoch) / 1000).floor();
}
void resetLogoutTimer() {
_timeLeft = DateTime.now();
_sessionTimer?.cancel();
_sessionTimer = Timer(Duration(seconds: _timeoutInSeconds), _logout);
}
void _logout() {
if (Config.authStatus.authenticated) {
ServiceLogin().logoutUser().then((result) {
Config.authStatus = AuthStatus();
_navigator.currentState.pushNamedAndRemoveUntil(
NavigationLinks.NAV_HOME, (Route<dynamic> route) => false);
});
}
}
}
Then use the SessionTimeoutHandler above in your main widget setup (see initState below).
class AppTaskTracker extends StatefulWidget {
#override
_AppTaskTrackerState createState() => _AppTaskTrackerState();
}
class _AppTaskTrackerState extends State<AppTaskTracker> {
final GlobalKey<NavigatorState> _navigator = GlobalKey<NavigatorState>();
#override
void initState() {
super.initState();
SessionTimeoutHandler(_navigator, Config.LOGOUT_TIMEOUT).installLogoutHandler();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
...
Take into account that SessionTimeoutHandler gets the navigator in order to redirect to home after automatic logout.