An easy Flutter state management library

Overview

EbloX

An easy Flutter state management library.It is similar to Bloc, but it uses a lot of annotations and separates business logic from UI through the concepts of Action and State.

Simpler, more reliable, easier to test !

Example

An example of a common counter.

Add dependency:

dependencies:
  eblox:
  eblox_annotation:

dev_dependencies:
  build_runner:
  eblox_generator:

New counter_view_model.dart

import 'package:eblox/eblox.dart';
import 'package:eblox_annotation/eblox_annotation.dart';
import 'package:flutter/cupertino.dart';

part 'counter_view_model.g.dart';

@bloX
class _CounterVModel extends Blox{

  @StateX(name:'CounterState')
  int _counter = 0;

  @ActionX(bind: 'CounterState')
  void _add() async{
    _counter ++;
  }

  @ActionX(bind: 'CounterState')
  void _sub(){
    _counter--;
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint('CounterVModel dispose...');
  }
}

Execute flutter pub run build_runner watch --delete-conflicting-outputs command will generate the counter_view_model.g.dart file in the current directory.

It will automatically generate Action and State for us. Next, write the UI and use these Actions.

import 'package:eblox/blox.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

import 'blox/counter_view_model.dart';

class CounterPage extends StatelessWidget {
  const CounterPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child:BloxBuilder<CounterVModel,CounterState>(
            create:()=>CounterVModel(),
            builder: (count) {
              return Center(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text("$count"),
                    ElevatedButton(
                      onPressed: () {
                        AddAction().to<CounterVModel>();
                      },
                      child: const Text("+"),
                    ),
                    ElevatedButton(
                      onPressed: () {
                        SubAction().to<CounterVModel>();
                      },
                      child: const Text("-"),
                    ),
                  ],
                ),
              );
            }),
      ),
    );
  }
}

So easy!

Usage

Derive a class from Blox, where we write business logic. This is the ViewModel in MVVM. Note that in order to facilitate annotation to generate code, the class must use the _ prefix. Finally, we used the @bloX annotation on this class.

@StateX is used to decorate the state we need, it will automatically generate a State class with a specified name for packaging the modified data:

// **************************************************************************
// BloxStateGenerator
// **************************************************************************

class CounterState<T> extends BloxSingleState<T> {
  CounterState(data) : super(data);
}

If you do not specify a name, the state class will be generated according to the default rules. E.g:

@StateX()
Color _color = Colors.white; 

Will generate ColorState.

@ActionX is used to generate the Action class, and the name can also be specified. The bind is used to specify which State class to associate this Action with. In addition, it also associates the decorated method with the generated Action, and this method is called when the Action is sent.

An @AsyncX annotation is also currently provided to decorate asynchronous state:

part 'search_view_model.g.dart';

@bloX
class _SearchVModel extends Blox{

  @AsyncX(name: 'SongListState')
  SongListModel _songModel = SongListModel();

  @bindAsync
  @ActionX(bind: 'SongListState')
  BloxAsyncTask<SongListModel> _search(String name){
    return (){
      return  SearchService.search(name);
    };
  }
}

@ActionX decorated method can also declare parameters, the generated class will automatically include:

// **************************************************************************
// BloxActionGenerator
// **************************************************************************

class SearchAction extends BloxAction {
  SearchAction(String name) : super.argsByPosition([name]);
}

To associate an Action method with an asynchronous state, you need to add another annotation @bindAsync. The method annotated by @bindAsync must return the type BloxAsyncTask<T>, and the generic T is the data we need to load asynchronously type.

In the UI, you can use BloxView to handle asynchronous states:

class SearchPage extends StatelessWidget {
  SearchPage({Key? key}) : super(key: key);

  final TextEditingController _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Song search'),),
      body: SafeArea(
        child: Column(
          children: [
            TextField(
              controller: _controller,
              decoration: InputDecoration(
                contentPadding: const EdgeInsets.symmetric(horizontal: 16),
                  suffix: IconButton(
                icon: const Icon(Icons.search_rounded),
                onPressed: (){
                  if(_controller.text.isNotEmpty) {
                    SearchAction(_controller.text).to<SearchVModel>();
                  }
                },
              )),
            ),
            Flexible(
                child: BloxView<SearchVModel, SongListState<SongListModel>>(
              create: () => SearchVModel(),
              onLoading: () => const Center(child: CircularProgressIndicator()),
              onEmpty: ()=> const Center(child: Text("Empty")),
              builder: (state) {
                return ListView.builder(
                    itemCount: state.data.songs.length,
                    itemBuilder: (ctx, i) {
                      return Container(
                        alignment: Alignment.center,
                        height: 40,
                        child: Text(state.data.songs[i],style: const TextStyle(color: Colors.blueGrey,fontSize: 20),),
                      );
                    });
              },
            )),
          ],
        ),
      ),
    );
  }
}

BloxView provides onLoading, onEmpty, onError,builder to handle the UI display during and after loading.

Note that if you want onEmpty to be valid, then your custom data type should mixin BloxData:

class SongListModel with BloxData{

  SongListModel({UnmodifiableListView<String>? songs}){
    if(songs !=null) this.songs = songs;
  }

  UnmodifiableListView<String> songs = UnmodifiableListView([]);

  @override
  bool get isEmpty => songs.isEmpty;
}

Please check here for detailed examples.

You might also like...

💻 Flutter clean architecture using the bloc & cubit library for state management

💻 Flutter clean architecture using the bloc & cubit library for state management

Egymation 🎥 · This application was developed using a well-defined and decoupled architecture, following TDD (test-driven programming) as a working me

Nov 21, 2022

An extension to the bloc state management library which automatically persists and restores bloc states.

An extension to the bloc state management library which automatically persists and restores bloc states.

⚠️ Attention: This repository has been moved to https://github.com/felangel/bloc and is now read-only! An extension to the bloc state management libra

Nov 17, 2022

A state management library that enables concise, fluid, readable and testable business logic code.

A state management library that enables concise, fluid, readable and testable business logic code.

Creator is a state management library that enables concise, fluid, readable, and testable business logic code. Read and update state with compile time

Dec 24, 2022

Flutter-minimalist - Flutter Minimalist state management example

Flutter-minimalist - Flutter Minimalist state management example

Flutter Minimalist state management example Because the official Flutter website

Mar 31, 2022

Flutter bloc example - An app for State management using BLoC pattern in Flutter

Flutter bloc example - An app for State management using BLoC pattern in Flutter

Flutter BLoC My first app for State management using BLoC pattern in Flutter Col

Jun 16, 2022

Flutter getx template - A Flutter Template using GetX package for State management, routing and Dependency Injection

Flutter getx template - A Flutter Template using GetX package for State management, routing and Dependency Injection

Flutter GetX Template (GetX, Dio, MVVM) This Flutter Template using GetX package

Aug 27, 2022

⚡FQuery is a powerful async state management solution for flutter. It caches, updates and fully manages asynchronous data in your flutter apps.

⚡ FQuery is a powerful async state management solution for flutter. It caches, updates and fully manages asynchronous data in your flutter apps. It ca

Dec 22, 2022

Doctor Consultation App in Flutter containing splash screen on boarding screen Routing state management Dash board Bottom navigation Decorated Drawer and Doctors Screen in the last.

Doctor Consultation App in Flutter containing splash screen on boarding screen  Routing  state management Dash board Bottom navigation Decorated Drawer and Doctors Screen in the last.

Online doctor Consultation App UI in Flutter Doctor Consultation App UI in Flutter Visit Website Features State Management Navigation Bar Responsive D

Jan 1, 2023

A project built to learn Flutter state management

Tienda Tienda is a simple product store mobile application. Tienda is a flutter application which was solely built to learn App state and local state

Nov 28, 2021
Owner
arcticfox
公众号:编程之路从0到1
arcticfox
An easy Flutter state management library

EbloX An easy Flutter state management library.It is similar to Bloc, but it uses a lot of annotations and separates business logic from UI through th

arcticfox 9 Oct 29, 2022
Nexus is a state management library that makes it easy to create and consume your application's reactive data to the user interface.

Nexus ?? Nexus is a state management library that makes it easy to create and consume your application's reactive data to the user interface. With nex

Gor Mkhitaryan 3 Sep 7, 2022
Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to tidily bound separated logic into complex solution.

Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to

Roman Hornak 23 Feb 23, 2022
Practice building basic animations in apps along with managing app state by BLoC State Management, Flutter Slider.

Practice building basic animations in apps along with managing app state by BLoC State Management including: Cubit & Animation Widget, Flutter Slider.

TAD 1 Jun 8, 2022
A powerful state machine for MobX management, that can be used in almost any application state.

A powerful state machine for MobX management, which can be used in almost any application state. It has 3 states - loading, success, error - and is pe

Daniel Magri 8 Oct 31, 2022
Shopify Tag and Product Management App using Flutter and Riverpod State Management

Myshopify App A Simple Flutter Application project to get List of Tags, Products and Product Details from shopify https://shopicruit.myshopify.com/adm

Idowu Tomiwa 5 Nov 12, 2022
Easy Form State Management using BLoC pattern

?? Dart and Flutter Package ?? Easy Form State Management using BLoC pattern ?? Wizard/stepper forms, asynchronous validation, dynamic and conditional fields, submission progress, serialization and more! ??

GiancarloCode 406 Jan 8, 2023
Minimalist and Easy State Management for Bloc Inspired from Dart Generics.

Velocity Bloc Getting started In the pubspec.yaml of your flutter project, add the following dependency: dependencies: ... velocity_bloc: <latest_

Sangam Singh 18 Aug 1, 2023
An atomic state management library for dart (and Flutter). Simple, fast and flexible.

nucleus An atomic dependency and state management toolkit. Design goals Simplicity - simple API with no surprises Performance - allow for millions of

Tim 12 Jan 2, 2023