Skip to main content

Services

The CotR classes are meant to be used at the view level but there are situations where you need a service to be accessed throughout your entire app.

For example, an authentication service that manages the user's information and authentication state can be utilized by your LoginView, HomeView, and FeedView for different reasons:

Global service

code_on_the_rocksโ€‹

You can implement this design using the code_on_the_rocks package by creating a new ViewModel/ViewModelBuilder and placing it at the root of your app's widget tree.

ViewModelโ€‹

class AuthenticationViewModel extends ViewModel<AuthenticationViewModel> {
bool loggedIn = false;
String? name;
String? email;

void setLoggedIn(bool val) {
setState(() => loggedIn = val);
}

void setName(String val) {
setState(() => name = val);
}

void setEmail(String val) {
setState(() => email = val);
}

static AuthenticationViewModel of_(BuildContext context) => getModel<AuthenticationViewModel>(context);
}

ViewModelBuilderโ€‹

class AuthenticationViewModelBuilder extends ViewModelBuilder<AuthenticationViewModel> {
const AuthenticationViewModelBuilder({
super.key,
required super.builder,
});

@override
State<StatefulWidget> createState() => AuthenticationViewModel();
}

Then you can add the new ViewModelBuilder at the root of your app:

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Global Service Demo',
home: AuthenticationViewModelBuilder(builder: (context, model) {
return const HomeView();
}),
);
}
}

Now, anywhere in your app you can access the AuthenticationViewModel ("service") like any other InheritedWidget:

AuthenticationViewModel authModel = getModel<AuthenticationViewModel>(context);

get_itโ€‹

ioc_containerโ€‹