Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Binder — State Management in Flutter

It is a lightweight, yet powerful way to hold together your application states with your business logic which will be responsible for updating it.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.

Table of Contents:-

Flutter — Introduction

State management

Installation

Code Implementation

Final Output

Conclusion

Github Link


Flutter — Introduction:-

Developing a mobile application is quite a challenging task. There are many frameworks we’re provided with for creating a mobile application. Android provides us with a native framework based on Java language and also, and iOS provides a native framework based on Objective-C / Swift language.

However, to develop an application supporting both OSs, we have to code in two different languages using two different frameworks. To help overcome this convolution, there exist mobile frameworks supporting both OSs. These frameworks range from simple HTML-based hybrid mobile application frameworks (which use HTML for User Interface and JavaScript for application logic) to complex language-specific frameworks (which does the heavy lifting of converting code to native code). Moreover, these frameworks always have many disadvantages also, one of the main drawbacks being their slow performance.

Flutter is a framework that allows developers to build beautiful and responsive user interfaces for multiple platforms using a single codebase. It uses the Dart programming language, which is also developed by Google, to write applications. Flutter provides a layered architecture with customizable widgets, a reactive framework, and a rendering engine, enabling developers to create visually appealing and performant apps.

State Management:-

In Flutter, state management is a crucial aspect of building robust and efficient applications. With the ever-increasing complexity of modern applications, it becomes essential to manage the state of the app in a structured and efficient manner. One popular state management approach in Flutter is using a package called “Binder.” In this article, we will explore Binder and how it can help developers in managing the state of their Flutter applications effectively.

> What is Binder?

The binder is a state management package for Flutter that aims to simplify the process of managing the application state and making it more predictable. It provides a declarative and reactive way of handling state changes, allowing developers to build scalable and maintainable applications.

> Key Concepts of Binder:

State: In Binder, the state represents the current data of your application. It can be as simple as a single value or a complex data structure. The state is immutable, meaning it cannot be modified directly. Instead, you create a new state instance whenever a change occurs.

Binder: A Binder is a class that encapsulates a specific piece of state in your application. It is responsible for managing the state and notifying the widgets that depend on it whenever a change occurs. Binders can be combined to represent the entire state of your application.

Binding: Binding is the process of connecting a widget to a specific piece of state managed by a Binder. When a widget is bound to a state, it automatically rebuilds whenever the state changes, ensuring that the UI stays in sync with the data.

Actions: Actions represent events or user interactions that can cause changes in the state. Binders can define actions that encapsulate the logic for modifying the state in response to these events. Actions can be triggered from various sources, such as user input or network responses.

Important classes for implementing Binder:-

  • BinderScope()

A widget that stores a part of the app state.

Any Flutter application must have at least one BinderScope. The more appropriate place to have it is at the root of the widget tree.

void main() => runApp(BinderScope(child: MyApp()));
  • LogicLoader() —

A widget that can be used to load resources when it’s inserted in the tree.

For example, you can use this widget to load data from the repository, the first time this widget builds.

Installation:-

  1. Getting started with Binder:-

To start using Binder in your Flutter project, you need to follow a few simple steps:

a. Add the Binder dependency in the “dependency” section of your project’s pubspec.yaml file.binder: ^0.4.0

b. Define your model classes representing different parts of your app’s state.

c. Create a Binder instance and bind your models to it.

d. Use the provided BinderScope widget to wrap the parts of your UI that depend on the state.

e. Access and modify the state using the BinderScope and the model instances.

Code Implementation:-

Let’s understand binder more descriptively. Below is the project code which has been developed using Binder.

main.dart:-

void main() {
runApp(const App());
}

class App extends StatelessWidget {
const App({
Key key,
this.mockHome,
}) : super(key: key);

Final Widget mockHome;

@override
Widget build(BuildContext context) {
return BinderScope(
child: MaterialApp(
title: 'Binder Demo App',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
debugShowCheckedModeBanner: false,
home: const HomeView(),
),
);
}
}

Logic.dart :-

final homeViewLogicRef = LogicRef((scope) => HomeViewLogic(scope));

final usersRef = StateRef(const <User>[]);

class HomeViewLogic with Logic, BusyLogic implements Loadable {
const HomeViewLogic(this.scope);

@override
final Scope scope;

UserRepository get _userRepository => use(userRepositoryRef);

@override
Future<void> load() async {
busy = true;
final users = await _userRepository.getUsers();
write(usersRef, users);
busy = false;
}
}

view.dart :-

final userCountRef = Computed((watch) {
return watch(usersRef).length;
});

class HomeView extends StatelessWidget {
const HomeView({
Key key,
}) : super(key: key);

@override
Widget build(BuildContext context) {
return BinderScope(
overrides: [
busyRef.overrideWith(false),
homeViewLogicRef.overrideWithSelf(),
],
child: LogicLoader(
refs: [homeViewLogicRef],
child: const BusyListener(
child: Scaffold(
backgroundColor: AppColors.bgColor,
// appBar: AppBar(
// title: Text('Home', style: AppTextStyles.extraLargeWhiteText()),
// ),
body: SafeArea(child: UserGridView()),
),
),
),
);
}
}

class UserGridView extends StatelessWidget {
const UserGridView({
Key key,
}) : super(key: key);

@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(20.0),
child: Text("Users", style: AppTextStyles.xExtraLargeBlackText()),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(8),
child: GridView.builder(
physics: const BouncingScrollPhysics(),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
),
itemCount: context.watch(userCountRef),
itemBuilder: (context, index) {
final user = context.watch(usersRef.select((users) => users[index]));
return BinderScope(
overrides: [currentUserRef.overrideWith(user)],
child: const UserCellView(),
);
},
),
),
),
],
);
}
}

class UserCellView extends StatelessWidget {
const UserCellView({
Key key,
}) : super(key: key);

@override
Widget build(BuildContext context) {
final name = context.watch(currentUserRef.select((user) => user.name));
final initials = name.initials;
return Card(
child: InkWell(

onTap: () {
final user = context.read(currentUserRef);
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (context) {
return BinderScope(
overrides: [currentUserRef.overrideWith(user)],
child: UserView(name: name),
);
},
),
);
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Column(
children: [
CircleAvatar(
radius: 30,
backgroundColor: AppColors.primaryColor,
child: Text(
initials,
style: AppTextStyles.largeNormalTextLora(),
),
),
const SizedBox(
height: 10,
),
Text(
name,
textAlign: TextAlign.center,
style: AppTextStyles.regularMediumText(),
),
],
),
),
),
);
}
}

And others more descriptively below the Github repository link.

Final Output:-


Conclusion:-

State management is a critical aspect of building Flutter applications, and Binder offers a powerful solution to simplify this process. By leveraging the reactive and declarative nature of Binder, you can efficiently manage state updates and keep your UI components in sync with the underlying data. With its simplicity, scoped state management, and integration capabilities, Binder is a valuable tool to consider for your next Flutter project.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


Github link:

Find the source code of binder_demo:

GitHub – flutter-devs/binder_demo
A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…github.com


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

Your email address will not be published. Required fields are marked with *.