rebloc 0.0.5

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • new65

rebloc

A state management library for Flutter that combines aspects of Redux and BLoC (this readme assumes some familiarity with both). It's a personal project by redbrogdon, rather than an official library from the Flutter team. You can find it on pub, Dart's package manager.

Adding rebloc to your project

Add this line to the project dependencies in your pubspec.yaml:

  rebloc: ^0.0.4

And use this import:

import 'package:rebloc/rebloc.dart';

What's going on here

Rebloc is an attempt to smoosh together two popular Flutter state management approaches: Redux and BLoC. It defines a Redux-y single direction data flow that involves actions, middleware, reducers, and a store. Rather than using functional programming techniques to compose reducers and middleware from parts and wire everything up, however, it uses BLoCs.

img

The store defines a dispatch stream that accepts new actions and produces state objects in response. In between, BLoCs are wired into the stream to function as middleware and reducers. The stream for a simple, two-BLoC store might look like this, for example:

Dispatch ->
  BloC #1 middleware ->
  BLoC #2 middleware ->
  the action is converted into an accumulator (action and state together) ->
  BLoC #1 reducer ->
  BLoC #2 reducer ->
  resulting state object is emitted by store

There are two ways to implement BLoCs. The first is a basic Bloc<StateType> interface that allows direct access to the dispatch stream (meaning you can transform it, expand it, and do all sorts of other streamy goodness). The other is an abstract class, SimpleBloc<StateType>, that hides away interaction with the stream and provides a simple, functional interface.

Middleware methods can perform side effects like calling out to REST endpoints and dispatching new actions, but reducers should work as pure functions in keeping with Redux core principles. Middleware are also allowed to cancel actions.

Why does this exist?

State management is an open question for Flutter developers. I like the freedom of BLoCs, because a streaming interface can often turn what would be weird async patterns into easily understood transforms, maps, expands, and so on. On the other hand, I also like that the Redux pattern can offer things like easily composed reducers and middleware, great support for cross-cutting concerns like logging, and the potential for time-travel debugging if interest merits building those sorts of tools.

Thus I'd like to see if I can combine the two and get the parts I like from both. Also, it's a chance to test out...

ViewModelSubscriber

Also included in this library is a widget called ViewModelSubscriber. It looks for an InheritedWidget called StoreProvider above it to find a stream of app state objects to subscribe to. Then it converts each object that comes through the stream into a view model object and builds widgets with it. This is similar to a StreamBuilder, but with the benefit that a ViewModelSubscriber will ignore any state objects that don't cause a change to its view model.

What this means in practice is that if you're building a piece of UI that depends on one part of your overall app state, it will only be rebuilt and redrawn if that one particular bit of data changes. If you've got a list of complicated records, for example, you can use ViewModelSubscriber widgets to avoid rebuilding the entire list just because one field in one record changed.

Basic example

Imagine an app that just needs to track a list of int as its only state. You might have a class to represent the state of the app that looks like this:

class AppState {
  List<int> numbers;

  AppState(this.numbers);
}

You might want to add a new number to the list, so you create an Action class to trigger such a state change:

class AddNumberAction extends Action {
  final int newNumber;

  const AddNumberAction(this.newNumber);
}

To process that action, you'll need a BLoC, so you create one:

class NumbersBloc extends SimpleBloc<AppState> {
  @override
  AppState reducer(AppState state, Action action) {
    if (action is AddNumberAction) {
      final newList = List<int>.from(state.numbers)..add(action.newNumber);
      return AppState(newList);
    }

    return state;
  }
}

And you'll need a store to wire all this up for you, so you create one in main and use a StoreProvider to propagate it down the tree:

void main() {
  final store = Store<AppState>(
    initialState: AppState([1, 2, 3]),
    blocs: [
      NumbersBloc(),
    ],
  );

  runApp(
    StoreProvider<AppState>(
      store: store,
      child: HomeScreen(),
    ),
  );
}

To build widgets with the data and dispatch new actions, you add a ViewModelSubscriber to HomeScreen that looks like this:

ViewModelSubscriber<AppState, int>(
  converter: (state) => state.numbers.reduce((sum, val) => sum + val),
  builder: (context, dispatcher, model) => Center(
    child: Column(
      children: [
        Text('Sum of all the numbers: $model'),
        RaisedButton(
          child: Text('Add 3'),
          onPressed: () => dispatcher(AddNumberAction(3)),
        ),
        RaisedButton(
          child: Text('Add 0'),
          onPressed: () => dispatcher(AddNumberAction(0)),
        ),
      ],
    ),
  ),
)

Now when your user taps on one of the buttons, an action is dispatched to the store. It's processed by the reducer and a new AppState object is created. If the user hit the 'Add 3' button, the ViewModelSubscriber will be rebuilt and show the new sum. If the user hit the 'Add 0' button, the ViewModelSubscriber will not be rebuilt, since the sum wasn't changed (even though there's a new number in the list).

If you'd like to do something fancy like log every action to the console, you can add a middleware function to the BLoC:

@override
FutureOr<Action> middleware(
    DispatchFunction dispatcher, AppState state, Action action) {
  if (action is AddNumberAction) {
    print('Adding a number: ${action.newNumber}.');
  }

  return action;
}

Examples

Two examples are included (a basic one, and a list-based one) so you can see the library in action. It's also used in the (currently being built) Voxxed Days conference app.

Feedback

I'm interested in whatever feedback other devs in the Flutter community may have, whether it's "This is awesome" or "This design is bad and you should feel bad." Feel free to file issues and feature requests, tweet at @RedBrogdon, and come join the conversation at the Flutter Dev Google group.

[0.0.4] - 8/27/2018.

  • First release in which I remembered to update the change log.
  • Two examples in place, plus the library itself.
  • Seems relatively stable.

example/lib/main.dart

// Copyright 2018 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:rebloc/rebloc.dart';

String _formatTime(DateTime time) {
  String hours = time.hour.toString().padLeft(2, '0');
  String minutes = time.minute.toString().padLeft(2, '0');
  String seconds = time.second.toString().padLeft(2, '0');
  String milliseconds = time.millisecond.toString().padLeft(3, '0');
  return '$hours:$minutes:$seconds.$milliseconds';
}

void main() => runApp(
      new MaterialApp(
        title: 'Rebloc Example',
        home: StoreProvider<AppState>(
          store: Store<AppState>(
            initialState: AppState.initialState(),
            blocs: [
              LoggerBloc(),
              LimitBloc(),
              IntBloc(),
              DoubleBloc(),
              StringBloc(),
              DescriptionBloc(),
            ],
          ),
          child: new MyHomePage(),
        ),
      ),
    );

class AppState {
  final int anInt;
  final double aDouble;
  final String aString;

  const AppState(this.anInt, this.aDouble, this.aString);

  const AppState.initialState()
      : anInt = 0,
        aDouble = 0.0,
        aString = "AAA";

  AppState copyWith({int anInt, double aDouble, String aString}) {
    return AppState(
      anInt ?? this.anInt,
      aDouble ?? this.aDouble,
      aString ?? this.aString,
    );
  }

  String toString() {
    return 'anInt is $anInt, aDouble is $aDouble, and aString is \'$aString\'';
  }
}

class IntAction extends Action {}

class DoubleAction extends Action {}

class StringAction extends Action {
  final String newChar;

  StringAction(this.newChar);
}

class DescriptionAction extends Action {}

class ResetAction extends Action {}

class IntBloc extends SimpleBloc<AppState> {
  @override
  AppState reducer(state, action) {
    if (action is IntAction) {
      return state.copyWith(anInt: state.anInt + 1);
    } else if (action is ResetAction) {
      return state.copyWith(anInt: 0);
    }

    return state;
  }
}

class DoubleBloc extends SimpleBloc<AppState> {
  @override
  AppState reducer(state, action) {
    if (action is DoubleAction) {
      return state.copyWith(aDouble: state.aDouble + 1.0);
    } else if (action is ResetAction) {
      return state.copyWith(aDouble: 0.0);
    }

    return state;
  }
}

class StringBloc extends SimpleBloc<AppState> {
  @override
  AppState reducer(state, action) {
    if (action is StringAction) {
      return state.copyWith(aString: '${state.aString}${action.newChar}');
    } else if (action is ResetAction) {
      return state.copyWith(aString: 'AAA');
    }

    return state;
  }
}

class DescriptionBloc extends SimpleBloc<AppState> {
  @override
  Action middleware(dispatcher, state, action) {
    if (action is DescriptionAction) {
      dispatcher(IntAction());
      dispatcher(DoubleAction());
      dispatcher(StringAction('B'));
    }

    return action;
  }
}

/// Logs each incoming action.
class LoggerBloc extends SimpleBloc<AppState> {
  @override
  Future<Action> middleware(dispatcher, state, action) async {
    print('${action.runtimeType} dispatched. State: $state.');

    // This is just to demonstrate that middleware can be async. In most cases,
    // you'll want to cancel or return immediately.
    return await Future.delayed(Duration.zero, () => action);
  }
}

/// Limits each of the three values in [AppState] to certain maximums. This
/// [Bloc] must appear before the others in the list given to the [Store].
class LimitBloc extends SimpleBloc<AppState> {
  static const maxInt = 10;
  static const maxDouble = 10;
  static const maxLength = 10;

  @override
  Action middleware(
      DispatchFunction dispatcher, AppState state, Action action) {
    if ((action is IntAction && state.anInt == maxInt) ||
        (action is DoubleAction && state.aDouble == maxDouble) ||
        (action is StringAction && state.aString.length == maxLength)) {
      // Cancel (or "swallow") the action if a limit would be exceeded.
      return Action.cancelled();
    }

    return action;
  }
}

class IntDisplayWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ViewModelSubscriber<AppState, int>(
      converter: (state) => state.anInt,
      builder: (context, dispatcher, viewModel) {
        final dateStr = _formatTime(DateTime.now());

        return Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text('Value: $viewModel'),
              Text('Rebuilt at $dateStr'),
              SizedBox(height: 4.0),
              RaisedButton(
                child: Text('Increment'),
                onPressed: () => dispatcher(IntAction()),
              )
            ],
          ),
        );
      },
    );
  }
}

class DoubleDisplayWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ViewModelSubscriber<AppState, double>(
      converter: (state) => state.aDouble,
      builder: (context, dispatcher, viewModel) {
        final dateStr = _formatTime(DateTime.now());

        return Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text('Value: $viewModel'),
              Text('Rebuilt at $dateStr'),
              SizedBox(height: 4.0),
              RaisedButton(
                child: Text('Increment'),
                onPressed: () => dispatcher(DoubleAction()),
              )
            ],
          ),
        );
      },
    );
  }
}

class StringDisplayWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ViewModelSubscriber<AppState, String>(
      converter: (state) => state.aString,
      builder: (context, dispatcher, viewModel) {
        final dateStr = _formatTime(DateTime.now());

        return Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text('Value: $viewModel'),
              Text('Rebuilt at $dateStr'),
              SizedBox(height: 4.0),
              RaisedButton(
                child: Text('Increment'),
                onPressed: () => dispatcher(StringAction('A')),
              )
            ],
          ),
        );
      },
    );
  }
}

class DescriptionViewModel {
  final String description;

  DescriptionViewModel(AppState state) : description = state.toString() + "!";

  @override
  bool operator ==(other) {
    return description == other.description;
  }

  @override
  int get hashCode => description.hashCode;
}

class DescriptionDisplayWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ViewModelSubscriber<AppState, DescriptionViewModel>(
      converter: (state) => DescriptionViewModel(state),
      builder: (context, dispatcher, viewModel) {
        final dateStr = _formatTime(DateTime.now());

        return Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text('Value: ${viewModel.description}'),
              Text('Rebuilt at $dateStr'),
              SizedBox(height: 4.0),
              RaisedButton(
                child: Text('Increment everything'),
                onPressed: () => dispatcher(DescriptionAction()),
              ),
              SizedBox(height: 8.0),
              RaisedButton(
                child: Text('Reset everything'),
                onPressed: () => dispatcher(ResetAction()),
              )
            ],
          ),
        );
      },
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    TextTheme textTheme = Theme.of(context).textTheme;

    return Scaffold(
      appBar: AppBar(title: Text('Rebloc example')),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Integer view model:', style: textTheme.subhead),
              IntDisplayWidget(),
              SizedBox(height: 24.0),
              Text('Double view model:', style: textTheme.subhead),
              DoubleDisplayWidget(),
              SizedBox(height: 24.0),
              Text('String view model:', style: textTheme.subhead),
              StringDisplayWidget(),
              SizedBox(height: 24.0),
              Text('Combined view model:', style: textTheme.subhead),
              DescriptionDisplayWidget(),
            ],
          ),
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  rebloc: ^0.0.5

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

Alternatively, your editor might support flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:rebloc/rebloc.dart';
  
Version Uploaded Documentation Archive
0.0.5 Sep 11, 2018 Go to the documentation of rebloc 0.0.5 Download rebloc 0.0.5 archive
0.0.4 Sep 4, 2018 Go to the documentation of rebloc 0.0.4 Download rebloc 0.0.4 archive
0.0.3 Aug 27, 2018 Go to the documentation of rebloc 0.0.3 Download rebloc 0.0.3 archive
0.0.2 Aug 27, 2018 Go to the documentation of rebloc 0.0.2 Download rebloc 0.0.2 archive
0.0.1 Aug 24, 2018 Go to the documentation of rebloc 0.0.1 Download rebloc 0.0.1 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
33
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
90
Overall:
Weighted score of the above. [more]
65
Learn more about scoring.

We analyzed this package on Sep 18, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.12.3
  • Flutter: 0.8.4

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Suggestions

Package is pre-v0.1 release.

While there is nothing inherently wrong with versions of 0.0.*, it usually means that the author is still experimenting with the general direction of the API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
flutter 0.0.0
meta ^1.1.5 1.1.6
rxdart ^0.18.1 0.18.1
Transitive dependencies
collection 1.14.11
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test
test ^1.3.0