How to build the architecture of a flutter app - flutter

I'm implementing a chat-based app in Flutter. I was thinking of using Provider package to create two main notifiers: UserService and ChatService. The first one handles the signIn (and all the other functions user-related), while the latter handles chat specific functions. However, the chatService needs to access the UserService for some functionalities. I tried to use ProxyProvider and this is the code:
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<UserService>(builder: (_) => UserService.instance()),
ChangeNotifierProxyProvider<UserService, ChatService>(builder: (_, user, chatService) => ChatService.init(user))
],
child: MaterialApp(
...
),
);
}
}
However, when I run the app, flutter throws this error:
Tried to use Provider with a subtype of Listenable/Stream (ChatService).
This is likely a mistake, as Provider will not automatically update dependents
when ChatService is updated. Instead, consider changing Provider for more specific
implementation that handles the update mechanism, such as:
ListenableProvider
ChangeNotifierProvider
ValueListenableProvider
Thank you!

It's not clear which "architecture" you are going to use, Provider is simply a mechanism to retrieve objects in the widget tree in a safe way.
Assuming you mean UserService and ChatService, and these are ChangeNotifiers (could be BLoC or anything else) - here's an example of how you'd hook them up with Provider:
main() {
runApp(MultiProvider(
providers: [
ChangeNotifierProvider<UserService>(create: (_) => UserService()),
ChangeNotifierProxyProvider<UserService, ChatService>(
create: (_) => ChatService(),
update: (_, userService, chatService) => chatService..userService= userService
),
],
child: MyApp(),
));
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Consumer<ChatService>(
builder: (context, chatService, _) => Text(chatService.currentUser.lastMessage) // or whatever you need to do
);
}
}

Related

Flutter: Show notifications from background processes

I'm trying to find a way to show notifications (like SnackBar) in the application that are initiated from outside of user interface.
Overall setup is this:
My application on the top has blocs defined:
Widget build(BuildContext context) => MultiBlocProvider(
providers: [
BlocProvider(create: (_) => WalletCubit()),
BlocProvider(create: (_) => NotificationCubit())
],
child: MaterialApp(...)
);
NotificationCubit is responsible for emiting notification states with only method notify:
class NotificationCubit extends Cubit<NotificationState> {
NotificationCubit() : super(NotificationInitial());
void notify(String message) {
emit(NotificationState(message));
}
}
Notifications are supposed to be shown via BlocConsumer:
class _MyHomePage extends StatelessWidget {
#override
Widget build(BuildContext context) => BlocConsumer<NotificationCubit,
NotificationState>(
listener: (context, state) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(state.message)));
},
builder: (context, state) => BlocBuilder<NavigationBloc, NavigationState>(
...
)
);
Another blocs have callbacks that are called by background processes like getting data from the network where notification have to be edited:
class WalletCubit extends Cubit<WalletState> {
WalletCubit(backgroundProvider) {
backgroundProvider.subscribe(_callback);
}
void _callback(String message) {
NotificationCubit().notify(message);
}
}
This code doesn't really work. I see that instance of NotificationCubit is created but the state emited never reaches the code in p.3. I assume I shouldn't create new instance but use one from the building context.
So I've modified blocs in p.1 this way:
Widget build(BuildContext context) => MultiBlocProvider(
providers: [
BlocProvider(create: (_) => NotificationCubit()),
BlocProvider(create: (context) => WalletCubit(context))
],
child: MaterialApp(...)
);
and calling notify() from p.4 this way:
class WalletCubit extends Cubit<WalletState> {
BuildContext _context;
WalletCubit(this._context, backgroundProvider) {
backgroundProvider.subscribe(_callback);
}
void _callback(String message) {
_context.read<NotificationCubit>().notify(message);
}
}
This approach works. However it seems to me it creates tight coupling of blocs with Flutter framework. I have an understanding that all blocs should do is emiting own states.
So my question is: what is the "proper" way to allow all blocs sending application global notifications?

Could not find the correct Provider<...> above this ContactsPage Widget

I'm experimenting with Flutter and I'm trying to build a simple app using the Providers pattern.
My Problem
I am trying to access a provider in one of the widgets and I'm getting this error once I get the required provider in the stateful widget class. I can't figure out what am I doing wrong here.
Error
Error: Could not find the correct Provider<ContactProvider> above this ContactsPage Widget
This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:
- You added a new provider in your `main.dart` and performed a hot-reload.
To fix, perform a hot-restart.
- The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.
- You used a `BuildContext` that is an ancestor of the provider you are trying to read.
Make sure that ContactsPage is under your MultiProvider/Provider<ContactProvider>.
This usually happens when you are creating a provider and trying to read it immediately.
...
The Code
main.dart
import 'package:ProvidersExample/provider_list.dart';
void main() async => runApp(Home());
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: providerList,
child: MaterialApp(
home: ContactsPage(),
)
);
}
}
providers_list.dart
List<SingleChildWidget> providerList = [
ChangeNotifierProvider(
create: (_) => ContactProvider(),
lazy: false,
)
];
The provider: contact_provider.dart
class ContactProvider extends ChangeNotifier{
List<Contact> _contactList = [];
// getter
List<Contact> get contacts {
return [..._contactList];
}
// setter
set contacts(List<Contact> newContacts) {
_contactList = newContacts;
notifyListeners();
}
...
The Widget contacts_page.dart
class ContactsPage extends StatefulWidget {
#override
_ContactsPageState createState() => _ContactsPageState();
}
class _ContactsPageState extends State<ContactsPage> {
#override
void initState(){
super.initState();
}
#override
Widget build(BuildContext context) {
// This line throws the error
ContactProvider _provider = Provider.of<ContactProvider>
(context, listen:false);
return Scaffold(
appBar: AppBar(
title: Text(
...
I think the reason is that you are referencing a list of providers which were created outside in provider_list.dart which does not have access to your context from your widget tree.
Try this instead:
List providerList(context) {
return [
ChangeNotifierProvider(
create: (context) => ContactProvider(),
lazy: false,
)
];
}
providerList() is now a method that takes in context, and uses that context to register your providers, and return it.
You should specify the type <T> when creating your provider so it knows which type you are looking for in the widget tree.
List<SingleChildWidget> providerList = [
ChangeNotifierProvider<ContactProvider>(
create: (_) => ContactProvider(),
lazy: false,
)
];

Flutter Authentication and Data Persistence with Provider Architecture

I come from a HTML/CSS/JQUERY for frontend background and mostly I have been a Nodejs backend developer.
However a project I took over was based on HTML/CSS/JQuery and PHP and I am doing quite well in that until they needed a mobile application.
So my choice was flutter since it was hot at that moment.
I have mastered flutter basics and took provider as my state management and also incorporated logic inside it.
However I have 2 issue that I am not being able to figure out.
One is state persistence in provider even when app is forced closed.
Maintain login persistence unless logged out and clear state if logged out.
For 1. I haven't been able to figure out a concrete solution except Application Storage but then I would have to write alot of code more to store all the data and class into it.
For 2. I have done some experimental method as below
runApp(
ChangeNotifierProvider(
create: (_) => UserRepository(), // Here is my auth state provider
child: MyApp(),
),
);
In UserRepository class user data like user id are stored in SharedPreferences which checks if there is userdata is stored or not hence Status becomes Authenticated or Uninitialized per condition.
Below is a Stateful widget that sets the status with respect to UserRepository
class _MyAppState extends State<MyApp> {
ProjectRepository projectRepository = ProjectRepository();
UIKeypadRepository uiKeypadRepository = UIKeypadRepository();
PODRepository podRepository = PODRepository();
Status currentStatus;
//Also there are more Change notifier class here that manages state of various features of the app
void initProviders() {
projectRepository = ProjectRepository();
uiKeypadRepository = UIKeypadRepository();
podRepository = PODRepository();
}
#override
void initState() {
currentStatus = Provider.of<UserRepository>(context, listen: false).status;
//if not logged out current status is authenticated
super.initState();
}
#override
Widget build(BuildContext context) {
return Consumer(builder: (context, UserRepository authStatus, child) {
if (currentStatus != Status.Authenticated) {
initProviders(); // this function is called and all changenotifier classes are reinitialized
}
return MultiProvider(
providers: [
ChangeNotifierProvider.value(value: projectRepository),
ChangeNotifierProvider.value(value: uiKeypadRepository),
ChangeNotifierProvider.value(value: podRepository),
],
//instead of create I used value so if classes are initialized initial values are taken else existing values are made available to below the widget tree
child: MaterialApp(
home: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
child: LandingPage())),
);
});
}
}
You can use authStateChanges() and StreamBuilder to get the authentication status.
Reference

Recommendation when using bloc pattern in flutter

When using flutter bloc what is the recommendation, is it recomended for each page to have its own bloc or can i reuse one block for multiple pages, if so how?
I think that the best solution is to have one BLoC per page. It helps you to always know in which state each screen is just by looking at its BLoC. If you want to show the state of each of your tabs independently you should create one BLoC for each tab, and create one Repository which will handle fetching the data. But if the state of every tab will be the same, (for example you fetch data only once for all of the screens, so you don't show loading screen on every tab) then I think that you could create just one BLoC for all of this tabs.
It is also worth to add, that BLoCs can communicate with each other. So you can get state of one BLoC from another, or listen to its state changes. That could be helpful when you decide to create separate BLoCs for tabs.
I have addressed this topic in my latest article. You can check it out if you want to dive deeper.
There are no hard-set rules about this. It depends on what you want to accomplish.
An example: if each page is "radically" from each other, then yes, a BLoC per page makes sense. You can still share an "application-wide" BLoC between those pages if some kind of sharing or interaction is required between the pages.
In general, I've noticed that usually a BLoC "per page" is useful as there are always specific things related for each page that you handle within their BLoC. You can the use a general BLoC to share data or some other common thing between them.
You can combine the BLoC pattern with RxDart to handle somewhat more complex interaction scenarios between a BLoC and the UI.
Sharing a BLoC is fairly simple, just nest them or use a MultiProvider (from the provider package):
runApp(
BlocProvider(
builder: (_) => SettingsBloc(),
child: BlocProvider(
builder: (_) => ApplicationBloc(),
child: MyApp()
)
)
);
and then you can just retrieve them via the Provider:
class MyApp extends ... {
#override
Widget build(BuildContext context) {
final settingsBloc = Provider.of<SettingsBloc>(context);
final appBloc = Provider.of<ApplicationBloc>(context);
// do something with the above BLoCs
}
}
You can share different bloc's in different pages using BlocProvider.
Let's define some RootWidget that will be responsible for holding all Bloc's.
class RootPage extends StatefulWidget {
#override
_RootPageState createState() => _RootPageState();
}
class _RootPageState extends State<RootPage> {
NavigationBloc _navigationBloc;
ProfileBloc _profileBloc;
ThingBloc _thingBloc;
#override
void initState(){
_navigationBloc = NavigationBloc();
_thingBloc = ThingBloc();
_profileBloc = ProfileBloc();
super.initState();
}
#override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<NavigationBloc>(
builder: (BuildContext context) => _navigationBloc
),
BlocProvider<ProfileBloc>(
builder: (BuildContext context) => _profileBloc
),
BlocProvider<ThingBloc>(
builder: (BuildContext context) => _thingBloc
),
],
child: BlocBuilder(
bloc: _navigationBloc,
builder: (context, state){
if (state is DrawProfilePage){
return ProfilePage();
} else if (state is DrawThingsPage){
return ThingsPage();
} else {
return null
}
}
)
)
}
}
And after that, we can use any of bloc from parent and all widgets will share the same state and can dispatch event on the same bloc
class ThingsPage extends StatefulWidget {
#override
_ThingsPageState createState() => _ThingsPageState();
}
class _ThingsPageState extends State<ThingsPage> {
#override
void initState(){
_profileBloc = BlocProvider.of<ProfileBloc>(context);
super.initState();
}
#override
Widget build(BuildContext context) {
return Container(
child: BlocBuilder(
bloc: _profileBloc,
builder: (context, state){
if (state is ThingsAreUpdated){
return Container(
Text(state.count.toList())
);
} else {
return Container()
}
}
)
);
}
}

How to use a provider inside of another provider in Flutter

I want to create an app that has an authentication service with different permissions and functions (e.g. messages) depending on the user role.
So I created one Provider for the user and login management and another one for the messages the user can see.
Now, I want to fetch the messages (once) when the user logs in. In Widgets, I can access the Provider via Provider.of<T>(context) and I guess that's a kind of Singleton. But how can I access it from another class (in this case another Provider)?
From version >=4.0.0, we need to do this a little differently from what #updatestage has answered.
return MultiProvider(
providers: [
ChangeNotifierProvider(builder: (_) => Auth()),
ChangeNotifierProxyProvider<Auth, Messages>(
update: (context, auth, previousMessages) => Messages(auth),
create: (BuildContext context) => Messages(null),
),
],
child: MaterialApp(
...
),
);
Thanks for your answer. In the meanwhile, I solved it with another solution:
In the main.dart file I now use ChangeNotifierProxyProvider instead of ChangeNotifierProvider for the depending provider:
// main.dart
return MultiProvider(
providers: [
ChangeNotifierProvider(builder: (_) => Auth()),
ChangeNotifierProxyProvider<Auth, Messages>(
builder: (context, auth, previousMessages) => Messages(auth),
initialBuilder: (BuildContext context) => Messages(null),
),
],
child: MaterialApp(
...
),
);
Now the Messages provider will be rebuilt when the login state changes and gets passed the Auth Provider:
class Messages extends ChangeNotifier {
final Auth _authProvider;
List<Message> _messages = [];
List<Message> get messages => _messages;
Messages(this._authProvider) {
if (this._authProvider != null) {
if (_authProvider.loggedIn) fetchMessages();
}
}
...
}
Passing another provider in the constructor of the ChangeNotifierProxyProvider may cause you losing the state, in that case you should try the following.
ChangeNotifierProxyProvider<MyModel, MyChangeNotifier>(
create: (_) => MyChangeNotifier(),
update: (_, myModel, myNotifier) => myNotifier
..update(myModel),
);
class MyChangeNotifier with ChangeNotifier {
MyModel _myModel;
void update(MyModel myModel) {
_myModel = myModel;
}
}
It's simple: the first Provider provides an instance of a class, for example: LoginManager. The other Provides MessageFetcher. In MessageFetcher, whatever method you have, just add the Context parameter to it and call it by providing a fresh context.
Perhaps your code could look something like this:
MessageFetcher messageFetcher = Provider.of<ValueNotifier<MessageFetcher>>(context).value;
String message = await messageFetcher.fetchMessage(context);
And in MessageFetcher you can have:
class MessageFetcher {
Future<String> fetchMessage(BuildContext context) {
LoginManager loginManager = Provider.of<ValueNotifier<LoginManager>>(context).value;
loginManager.ensureLoggedIn();
///...
}
}
Seems like this would be a lot easier with Riverpod, especially the idea of passing a parameter into a .family builder to use the provider class as a cookie cutter for many different versions.