Flutter bloc with calling api on an interval - flutter

I'm working on an app that accesses two api's that contain location data that updates regularly (every 5 seconds or so). I want to utilize flutter and flutter_bloc to manage my state, but I'm not sure where the interval would come into play. I understand bloc and how the ui interacts with it with BlocBuilder and BlocProvider, as well as providing a repository that handles the api calls. What I'm not sure about is where to put the interval/timer. My idea was to do a normal bloc setup:
class DataBloc extends Bloc<DataEvent, DataState> {
//constructor
#override
Stream<DataState> mapEventToState(DataEvent event) async* {
if (event is FetchData) {
var data = repository.getData();
yield* _mapFetchDataToState(data);
}
}
}
In the ui:
class MainPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
final dataBloc = BlocProvider.of<DataBloc>(context);
Timer.periodic(fiveSeconds, (Timer t) => dataBloc.add(FetchData()));
return ui stuff
}
}
But I'm not sure if this is the right way to leverage BLoCs and/or timers. But I basically need to call the api on an interval and then have the data update in my ui without a full refresh of all the widgets. They're going to be icons on a google map, and I want the icons to update their locations when the data I pull is updated. How can I accomplish this? For reference, I've looked at the flutter_bloc docs for the timer app here and I thought it was a little overkill and that my idea above was simpler, just not sure if this is the right way. I'm pretty new to flutter so any help would be appreciated.

I'd recomend not to put initializing code inside build. Make it a StatefulWidget and add a dispose method to clear the timer. And inside initState setup the timer.
There's no right way in programming. There are best practices, so as long as it work for your use case is ok.

I would either put the timer into the bloc/cubit because its part of your logic and not of your ui.
Or if you use a repository I would probably use a stream listen to it in your bloc and periodically update the stream in your repo.
But any better suggestions are more than welcome, because I am also looking for some kind of 'the way to do'...

Related

Why should I use Provider in Mobx Flutter?

The official Mobx documentation for Flutter says that in order to transfer data correctly, you must use a Provider and refer to the context to retrieve the data.
But why can't I just call the Mobx class at the root of the application and access the global variable to get the data?
CbtStore cbt = CbtStore();
void main() async {
runApp(const MyApp());
}
Why should I be doing this?
void main() async {
runApp(MultiProvider(
providers: [
Provider<CbtStore>(create: (_) => CbtStore()),
],
child: MyApp()));
}
And how do I refer to Mobx inside the widget methods in that case, for example, if I want to call the action in the Mobx class in initState method? Now I do it in the following way. But when using Provider in initState there is no context.
#override
void initState() {
cbt.init();
super.initState();
}
Provider is used only for dependency injection with mobx. It is not used for state changes.
Now when you are using mobx you don't need a stateful widget in most cases because you are handling your state changes inside your mobx store and if there is any changes in the state we use Observer to change ui.
if want something to initialise with the screen than prefer using constructor of mobx class rather then initState.
for example,
class MyStore = _MyStore with _$MyStore;
abstract class _MyStore with Store {
_MyStore(){
getData();
}
}
Now don't use global providers for your all of store. Only Initialise a provider whenever you need it. So when you push a route wrap it with a provider so that Provider.of(context); can find it. Only use global store if it required globally.
You mentioned creating an instance of store to use it. When you initialise a store in stateless widget it, the data will get destroyed when you close the screen and when you reopen it everything will start all over again. It is useful when you don't need to maintain state after screen pops. It will based on your use case.
You should do what works best for your use case.
The reason why providers are useful is that they can be provided where needed. This could be in the application root, but also somewhere deeper in the widget tree.
Another advantage of the providers is that you can have a provider that notifies listeners. Widgets will rebuild automatically in this case, which can be useful if you have stored and need data to update everywhere in the application.
The initState does indeed not allow the use of providers directly. There are 3 solutions for this:
Don't have the provider listing (Provider.of(context, listen: false); This allows you to use the methods, but not listen to changes.
Use the provider in the build method, using the consumer.
I am by no means an expert on flutter, but this is just what I have experienced so far.

How do I use Flutters Navigator with a BLoC setup?

I am writing an app that is making use of Cubits for state management. It is an audiobook player and you can look up the different audiobooks and display them. Then jump to the author or the series and explore around your library.
As it stands at the moment the different pages you move between are being rendered using a BLoC builder as follows.
class ScreenSelector extends StatelessWidget {
#override
Widget build(BuildContext context) {
return BlocBuilder<ScreenCubit, ScreenState>(builder: (context, state) {
if (state is HomeScreenState) {
return HomeScreen();
}
if (state is BookScreenState) {
return BookScreen(bookId: state.bookId);
}
return null;
});
}
}
There are genre, author and series screens as well that will work the same as the book screen. There is a cubit that is emitting the appropriate state hooked up to different clickable widgets on the home and book page. This all works as expected. There is also an authorization flow that is worked to either render the HomeScreen or go to the Loginscreen. This also works nicely.
But i'd like to use a navigator instead so you can go backwards to previous pages. That seems like the right way to navigate but i'm lost on getting Navigator to work with BLoC.
I tried constructing the MaterialPageRoutes and pushing them when the state changes instead of loading the page and I tried converting the BlocBuilder to a BlocListener. Trying to push the page in the BlocBuilder did nothing and the BlocListener would only ever throw an exception.
If anybody has a pointer to how I might go about doing this or knows of a simple example of using Cubits with Navigator 1.0 in flutter I would be most grateful. I looked around but all of the examples I found either mixed in an authorization example and I got lost.
I expect i'm approaching the problem incorrectly but i'm not sure where I have gone off track.
Turns out I just have really crappy GoogleFu and you can find the solution to the problem at
https://bloclibrary.dev/#/recipesflutternavigation
It has a nice recipe that explains it well by the author of Bloc

How do I implement a version of Flutter's WidgetsBindingObserver without using state?

I am building a flutter app and I need to call a method in a provider when the app goes into background.
I can easily do this by creating a Stateful Widget using the WidgetsBindingObserver (like the example here).
Is there a way to do this without needing a Stateful Widget? Provider is a great architecture and state is an anti-pattern.
Possibly, You could try creating a class that isn't a widget and extending WidgetsBindingObserver.
Something like this perhaps
class MyListener extends WidgetsBindingObserver {
MyListener({this.providerInstance}){
WidgetsBinding.instance.addObserver(this);
};
MyProvider providerInstance;
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
providerInstance.doSomethingWithState(state)
}
}
Then implement the listener say in main() or yourApp() where ever your Provider setup is.
Thing is, there really isn't any issue with having a stateful widget at the root of your app somewhere as in the example. I honestly don't think your Anti pattern argument holds any relevance. Its common practice in flutter to have statefull and not statefull widgets.
By not having the statefull widget your just having to keep the state somewhere else, i.e. where ever it is your configuring your providers.

Flutter: How to track app lifecycle without a widget

I'm involved with the FlutterSound project which is shipped as a package containing an api that, for the purposes of this question, doesn't contain a widget.
The api needs to handle events when the application changes its state (AppLifecycleState.pause/resume). (we need to stop/resume audio when the app is paused/resumed).
I can see how to do this in a widget using WidgetsBindingObserver but the api needs this same info without having to rely on a widget.
The SchedulerBinding class has a method handleAppLifecycleStateChanged which seems to provide the required info but its unclear how to implement this outside of a widget.
Below is a code sample that can listen to AppLifecycleState change events without directly involving a widget:
import 'package:flutter/material.dart';
class MyLibrary with WidgetsBindingObserver {
AppLifecycleState _state;
AppLifecycleState get state => _state;
MyLibrary() {
WidgetsBinding.instance.addObserver(this);
}
/// make sure the clients of this library invoke the dispose method
/// so that the observer can be unregistered
void dispose() {
WidgetsBinding.instance.removeObserver(this);
}
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
this._state = state;
}
void someFunctionality() {
// your library feature
}
}
Now you can instantiate the library in a flutter widget, for instance, from which point it will start listening to any change in AppLifecycleState.
Please note that, the above code doesn't take care of redundant bindings. For example, if the client of your library is meant to initialize the library more than once in different places, the didChangeAppLifecycleState() method will be triggered multiple times per state change (depending on the number of instances of the library that were created). Also I'm unsure whether the solution proposed conforms to flutter best practices. Nevertheless it solves the problem and hope it helps!

Flutter BLoC: managing the state of primary data types

I am developing a mobile application using Flutter. I am new to Flutter. I am using BLoC for state management. I know that it is specially designed for management async execution. But also the purpose of BLoC is for state management. But I am a little bit confused and not quite sure how to handle the primary data types in BLoC.
Let's imaging the I have a button and an image. The functionality would be that when the button is clicked, the visibility of the image will be toggled. Literally, we just need to use a boolean variable to manage the state of the image. This is how I would implement it.
I have a bloc class called HomeBloc with the following implementation.
class HomeBloc {
bool _isImageDisplayed = true;
bool get isImageDisplayed => _isImageDisplayed;
void set isImageDisplayed(bool displayed) {
this._isImageDisplayed = displayed;
}
//the rest of the code for other functionalities goes here
}
final homeBloc = HomeBloc();
Then in the HomePage widget, I update the state of the image like this inside the setState method when the button is clicked.
this.setState(() {
homeBloc.isImageDisplayed = false;
});
My question is that "is it the standard way to manage primary data type in the BLoC in Flutter"? Is this the best practice? Do we need to use StreamBuilder? Do we even need to manage it inside the BLoC?
It's not the best practice I guess, as using setState becomes really hard on big applications and re-rendering widgets that don't change for no reason. Imagine making an e-commerce app and you just go to the product page, you add the product you like into the cart, but you have designed in your home page a cart icon with a red dot with a number inside it to specify how much products you got in your cart, so you handle the state of that icon in the main.dart file by passing a function that setState the home page route or maybe the whole application, it's hard, isn't it?.
Thankfully, BLoC and Provider patterns are basically using setState but in a better way so you don't have to re-render the whole page just for a small change in a text or something else, but you just re-render a specific widget in your widget tree.
I also recommend using BLoC Provider which is built on Provider and RxDart (Streams) as it makes great isolation between UI code and business code.
Check Provider and BLoC Provider.