Using BLoC pattern with service layer

A BLoC that only processes events from a widget and emits states based on its own logic is fairly simple once you know the concept. As soon as other components such as services are involved, things get a little bit more complicated. This tutorials aims for an understandable explanation on how to add a service dependency to a BLoC.

In order for this tutorial to mainly focus on the connection to the service, we use an already existing project to start from. This also serves the purpose of increasing the level of comprehensibility as it’s not only theory. The project this tutorial is based on is the basic calculator whose code can be found here. Its creation was documented in this tutorial, applying the BLoC pattern in this tutorial.

Flutter calculator with history
The final calculator displaying its history

Theory

What we have so far is a calculator that enables the user to execute basic operations. Let’s extend it by a history of executed calculations. Since these calculations should persist over multiple app starts, we use the shared_preferences to store them. The resulting call hierarchy is supposed to look like this:

Flutter BLoC service layer call hierarchy
Flutter BLoC service layer call hierarchy

Implementation

First thing we are going to do is implementing the service. We know both of the functionalities this service should have: storing a calculation (adding it to the existing history) and fetching the existing history.

The shared preferences package only supports primitive data types. That’s why we need to serialize the data we want to store. This way, we can just store and load a string that represents the list of calculations.

Extending our model

To be able to serialize it, we need to extend the CalculationModel:

import 'package:equatable/equatable.dart';

class CalculationModel extends Equatable {
...

  CalculationModel.fromJson(Map<String, dynamic> json)
      : firstOperand = json['firstOperand'],
        operator = json['operator'],
        secondOperand = json['secondOperand'],
        result = json['result'];

  Map<String, dynamic> toJson() =>
      {
        'firstOperand': firstOperand,
        'operator': operator,
        'secondOperand': secondOperand,
        'result': result,
      };

...
}

We follow the proposed implementation introduced in the official docs and add a toJson() and a fromJson() method. These should be self-explanatory. Every property of the class is mapped to or from a JSON property.

Now that we have the possibility to serialize our model, we can continue with the core logic of our new feature: the service.

Implementing the service

import 'dart:convert';

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

import '../calculation_model.dart';

class CalculationHistoryService {
  static String _sharedPreferenceKey = 'calculation_history';

  CalculationHistoryService({
    @required this.sharedPreferences
  }) : assert (sharedPreferences != null);

  SharedPreferences sharedPreferences;

  List<CalculationModel> fetchAllEntries() {
    List<CalculationModel> result = <CalculationModel>[];

    if (!sharedPreferences.containsKey(_sharedPreferenceKey)) {
      return [];
    }

    List<dynamic> history = jsonDecode(
        sharedPreferences.getString(_sharedPreferenceKey)
    );

    for (Map<String, dynamic> entry in history) {
      result.add(
        CalculationModel.fromJson(entry)
      );
    };

    return result;
  }

  Future<bool> addEntry(CalculationModel model) async {
    List<CalculationModel> allEntries = fetchAllEntries();
    allEntries.add(model);

    return sharedPreferences.setString(
      _sharedPreferenceKey,
      jsonEncode(allEntries)
    );
  }
}

The content of the service is quite overseeable. The most important thing: the SharedPreferences class is a constructor argument which makes it necessary to inject it into our service. This is very crucial as it guarantees the testability of our class by enabling us to mock the SharedPreferences class inside of the tests.

It’s also worth noting that we check for the existence of the key before we fetch the entries. If it’s not there, we return an empty list. So we prevent the possibility of returning null. This is a good practice when working with lists.

Other than that we just use the usual jsonEncode() and jsonDecode() functions to store and load our data. Since an array is a valid JSON payload, this serves our purpose.

Testing the service

The functionality of our service might be overseeable. However, I strongly recommend to test every component. That way, we can also verify we have implemented it in an isolated way and have covered the edge cases.

Let’s think of the test cases we have before we write the actual tests:

  • SharedPreferences.setString() is called once when storage key exists
  • SharedPreferences.getString() is called once when storage key exists (need to check for entries before adding one)
  • It properly fetches all entries from shared preferences if storage key exists
  • It properly fetches empty list if nothing has been stored yet
  • If there is an invalid JSON string, the entry should be deleted and an empty list should be returned (as a corrupt JSON can not be repaired automatically and should be invalidated)
  • When the addEntry() method is called and the shared preferences hold an empty list, the SharedPreferences should be called with a list containing only the given calculation (as the proper JSON string)
  • When addEntry() when there’s already a list, the resulting JSON string should be the combined list with the new entry as the latest entry of the serialized list

Now that’s a great thing. While listing the test cases I realized that we don’t have the functionality of invalidation and deletion yet. We will write the tests now and hope to have only one failing test whose cause we will fix in the implementation afterwards.

import 'dart:convert';

import 'package:basic_calculator/calculation_model.dart';
import 'package:basic_calculator/services/calculation_history_service.dart';
import 'package:mockito/mockito.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:test/test.dart';

class MockSharedPreferences extends Mock implements SharedPreferences {}

void main () {
  group('Calculation history service', () {

    final sharedPrefKey = 'calculation_history';

    test('Shared preferences (getString) is called once when storage key exists', () async {
      String mockedJson = jsonEncode([]);

      MockSharedPreferences mock = _getMockSharedPreferences(
          sharedPrefKey, mockedJson, true
      );

      CalculationHistoryService(sharedPreferences: mock).fetchAllEntries();

      verify(mock.getString(sharedPrefKey)).called(1);
    });

    test('Properly fetches all entries from shared preferences if storage key exists', () async {
      CalculationModel expectedModel = _getCalculationModelAddSample();
      String mockedJson = jsonEncode([expectedModel.toJson()]);

      MockSharedPreferences mock = _getMockSharedPreferences(
        sharedPrefKey, mockedJson, true
      );

      List<CalculationModel> expectedResult = [expectedModel];

      expect(
        CalculationHistoryService(sharedPreferences: mock).fetchAllEntries(),
        expectedResult
      );
    });

    test('Properly fetches empty list if nothing has been stored yet', () async {
      String mockedJson = jsonEncode([]);

      MockSharedPreferences mock = _getMockSharedPreferences(
        sharedPrefKey, mockedJson, false
      );

      List<CalculationModel> expectedResult = [];

      expect(
        CalculationHistoryService(sharedPreferences: mock).fetchAllEntries(),
        expectedResult
      );
    });

    test('If there is corrupt JSON in the shared preferences, it is deleted and an empty list is returned', () async {
      MockSharedPreferences mock = _getMockSharedPreferences(
        sharedPrefKey, 'invalid JSON', true
      );

      expect(
        CalculationHistoryService(sharedPreferences: mock).fetchAllEntries(),
        []
      );

      verify(mock.getString(sharedPrefKey)).called(1);
      verify(mock.remove(sharedPrefKey)).called(1);
    });

    test('Shared preferences are called once when adding new entry on an empty list', () async {
      CalculationModel inputModel = _getCalculationModelAddSample();

      String mockedJson = jsonEncode([inputModel.toJson()]);

      MockSharedPreferences mock = _getMockSharedPreferences(
        sharedPrefKey, mockedJson, false
      );

      await CalculationHistoryService(sharedPreferences: mock).addEntry(
        inputModel
      );

      verifyNever(mock.getString(sharedPrefKey));
      verify(mock.setString(sharedPrefKey, mockedJson)).called(1);
    });

    test('Shared preferences are called once with the correct json string when adding new entry on an existing list', () async {
      CalculationModel inputModel = _getCalculationModelAddSample();

      String mockedExistingJson = jsonEncode([inputModel.toJson()]);

      MockSharedPreferences mock = _getMockSharedPreferences(
        sharedPrefKey, mockedExistingJson, true
      );

      String mockedExpectedJson = jsonEncode([
        inputModel.toJson(), _getCalculationModelSubtractSample().toJson()
      ]);

      await CalculationHistoryService(sharedPreferences: mock).addEntry(
        _getCalculationModelSubtractSample()
      );

      verify(mock.getString(sharedPrefKey)).called(1);
      verify(mock.setString(sharedPrefKey, mockedExpectedJson)).called(1);
    });
  });
}

MockSharedPreferences _getMockSharedPreferences(String sharedPrefKey, String mockedJson, bool containsKey) {
  MockSharedPreferences mock = MockSharedPreferences();
  when(mock.getString(sharedPrefKey))
    .thenAnswer((realInvocation) => mockedJson);
  when(mock.containsKey(sharedPrefKey))
    .thenAnswer((realInvocation) => containsKey);
  return mock;
}

CalculationModel _getCalculationModelAddSample() {
  CalculationModel inputModel = CalculationModel(
    firstOperand: 1,
    operator: '+',
    secondOperand: 1,
    result: 2
  );
  return inputModel;
}

CalculationModel _getCalculationModelSubtractSample() {
  CalculationModel inputModel = CalculationModel(
    firstOperand: 10,
    operator: '-',
    secondOperand: 6,
    result: 4
  );
  return inputModel;
}

I will not go into depth of unit testing in this article. There will be an article in the future covering that topic. However, I will give a high-level explanation on what’s happening:

We turn the SharedPreferences class into a mock. That means, we create a “copy” of that class that does nothing by itself and can be controlled by us. That means: we can change the behavior of methods.

Why would we want that? Well, let’s say we have a Camera class that abstracts from the actual hardware calls. During a unit test, we want to verify that the initialization is called. This would always lead to an error because in the test environment, there is no camera available since everything is executed in a simulated environment. So instead of an actual camera initialization we do “nothing” in this method. Seems pointless but this way we can verify that the method was called without receiving an error.

Same situation happens here: we use shared preferences. We don’t want the tests to always access the actual shared preferences of the phone. We don’t want to mess with real stored data since we don’t want to test shared preferences itself (this is the responsibility of the shared_preferences package). Instead, we want it to have a controlled behavior so that we can say if the content of the shared preferences is x then do y.

A good example is the second test. We mock the SharedPreferences class in a way that it returns a list with one (serialized) calculation in a list when getString() is called. We can then verify that this is also the response the fetchAllEntries() method is giving.

Basically we always make assumptions on the called methods and the return values when the shared preferences are set up in a certain way.

Flutter BLoC  service failed unit test results
Unit tests with one fail

Right, there was this one case that only came up during implementation of the tests. Let’s fix the implementation to make it a green tick:

  List<CalculationModel> fetchAllEntries() {
    List<CalculationModel> result = <CalculationModel>[];

    if (!sharedPreferences.containsKey(_sharedPreferenceKey)) {
      return [];
    }

    List<dynamic> history = [];

    try {
      history = jsonDecode(
          sharedPreferences.getString(_sharedPreferenceKey)
      );
    } on FormatException {
      sharedPreferences.remove(_sharedPreferenceKey);
    }

    for (Map<String, dynamic> entry in history) {
      result.add(
        CalculationModel.fromJson(entry)
      );
    };

    return result;
  }

If we repeat the tests now, everything should be fine:

Flutter BLoC service unit test results
Our successful test results

The great thing about this is: no matter what parts of the application we continue to implement now we can be sure that if anything fails, it’s most likely not the service that causes this issue. This gives us a lot of confidence when finding causes of issues.

Events, states and BLoC

Now it’s time to actually call the service! For this, we need to add an event that gives the view layer the opportunity to communicate to the BLoC: “Hey, please give me the list of recent calculations”.

class FetchHistory extends CalculationEvent {
  @override
  List<Object> get props =>  [];
}

Easy! The resulting states can be the general purpose state we already have because the UI does not have to react differently on the different state types. If we had a “Loading” state, we would have to implement it separately because the UI would display a loading indicator only when this event occurs.

What we need to is to extend the current state by the history:

import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';

import '../calculation_model.dart';

abstract class CalculationState extends Equatable {
  final CalculationModel calculationModel;
  final List<CalculationModel> history;

  const CalculationState({
    @required this.calculationModel,
    @required this.history
  }) : assert(calculationModel != null);

  @override
  List<Object> get props => [calculationModel, history];
}

class CalculationInitial extends CalculationState {
  CalculationInitial() : super(calculationModel: CalculationModel(), history: []);
}

class CalculationChanged extends CalculationState {
  final CalculationModel calculationModel;
  final List<CalculationModel> history;

  const CalculationChanged({
    @required this.calculationModel,
    @required this.history
  })
    : assert(calculationModel != null),
      super(calculationModel: calculationModel, history: history);

  @override
  List<Object> get props => [calculationModel, history];
}

It’s just a second constructor argument that must not be null and is of type List<CalculationModel>.

Now in the BLoC, every time we have yielded a state so far, we now have to add history as an argument. For this purpose, we can just provide List.of(state.history) to clone the existing history like this:

yield CalculationChanged(
  calculationModel: resultModel,
  history: List.of(state.history)
);

There are two situations, though, where we must provide the actual history. The first is when the UI requests the history (initially) and the second one is after a calculation because the list has updated.

  @override
  Stream<CalculationState> mapEventToState(
    CalculationEvent event,
  ) async* {
    ...
    if (event is FetchHistory) {
      yield CalculationChanged(
        calculationModel: state.calculationModel,
        history: calculationHistoryService.fetchAllEntries()
      );
    }
    ...
  }

This first case is fairly simple. If we receive the FetchHistory event, we return the existing model with the fetched history.

Stream<CalculationState> _mapCalculateResultToState(
    CalculateResult event,
  ) async* {
  ...
  CalculationModel newModel = CalculationInitial().calculationModel.copyWith(
    firstOperand: () => result
  );

  yield CalculationChanged(
    calculationModel: newModel,
    history: List.of(state.history)
  );

  yield* _yieldHistoryStorageResult(model, newModel);
}

Stream<CalculationChanged> _yieldHistoryStorageResult(CalculationModel model, CalculationModel newModel) async* {
  CalculationModel resultModel = model.copyWith(result: () => newModel.firstOperand);

  if(await calculationHistoryService.addEntry(resultModel)) {
    yield CalculationChanged(
      calculationModel: newModel,
      history: calculationHistoryService.fetchAllEntries()
    );
  }
}

In the case of a finished calculation, we first yield the calculation result like before and then yield the history that is fetched. Now we make use of the Stream the BLoC is working with which enables us to yield multiple states after an action.

For the sake of completeness: if we had tests for our bloc, we would have to adapt all of them with the history and write ones for the FetchHistory event. I will skip this here and handle this topic in a separate article.

Creating the widget

We have put a lot of effort in the logic. Now let’s come to a part that can be actually seen: the widget that displays the history.

import 'package:basic_calculator/calculation_model.dart';
import 'package:flutter/material.dart';

class CalculationHistoryContainer extends StatelessWidget{
  CalculationHistoryContainer({
    @required this.calculations
  });

  final List<CalculationModel> calculations;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 80,
      margin: EdgeInsets.only(left: 24, right: 24, bottom: 24),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(12)),
        boxShadow: [
          BoxShadow(
            blurRadius: 2.0,
            spreadRadius: 2.0,
            color: Colors.black12
          )
        ]
      ),
      child: ListView(
        padding: EdgeInsets.all(12),
        children: [
          for (var model in calculations)
            Text(
              '${model.firstOperand} ${model.operator} ${model.secondOperand} = ${model.result}',
              textAlign: TextAlign.center
            )
        ],
      )
    );
  }
}

The widget hat displays the history has a list of CalculationModel as its only constructor argument. The visual representation of the widget itself is a shadowed container with a height of 80 wrapped around a list view that displays the calculations as text line by line.

Now it’s time to insert the CalculationHistoryContainer into the existing main screen. There’s nothing much we need to do because we separated view and logic.

  @override
  void initState() {
    context.bloc<CalculationBloc>().add(FetchHistory());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CalculationBloc, CalculationState>(
      builder: (context, CalculationState state) {
        return Column(
          children: [
            ResultDisplay(
              text: _getDisplayText(state.calculationModel),
            ),
            Row(
              children: [
                _getButton(text: '7', onTap: () => numberPressed(7)),
                _getButton(text: '8', onTap: () => numberPressed(8)),
                _getButton(text: '9', onTap: () => numberPressed(9)),
                _getButton(text: 'x', onTap: () => operatorPressed('*'), backgroundColor: Color.fromRGBO(220, 220, 220, 1)),
              ],
            ),
            Row(
              children: [
                _getButton(text: '4', onTap: () => numberPressed(4)),
                _getButton(text: '5', onTap: () => numberPressed(5)),
                _getButton(text: '6', onTap: () => numberPressed(6)),
                _getButton(text: '/', onTap: () => operatorPressed('/'), backgroundColor: Color.fromRGBO(220, 220, 220, 1)),
              ],
            ),
            Row(
              children: [
                _getButton(text: '1', onTap: () => numberPressed(1)),
                _getButton(text: '2', onTap: () => numberPressed(2)),
                _getButton(text: '3', onTap: () => numberPressed(3)),
                _getButton(text: '+', onTap: () => operatorPressed('+'), backgroundColor: Color.fromRGBO(220, 220, 220, 1))
              ],
            ),
            Row(
              children: [
                _getButton(text: '=', onTap: calculateResult, backgroundColor: Colors.orange, textColor: Colors.white),
                _getButton(text: '0', onTap: () => numberPressed(0)),
                _getButton(text: 'C', onTap: clear, backgroundColor: Color.fromRGBO(220, 220, 220, 1)),
                _getButton(text: '-', onTap: () => operatorPressed('-'),backgroundColor: Color.fromRGBO(220, 220, 220, 1)),
              ],
            ),
            Spacer(),
            CalculationHistoryContainer(
              calculations: state.history.reversed.toList()
            )
          ],
        );
      },
    );
  }

We need to pull the BlocBuilder up in the widget hierarchy because state changes affect the whole Column now. This is because the CalculationHistoryContainer is now part of the Column as well.

In order to make the history appear when the widget is rendered, we also need to add the FetchHistory() event to the BLoC on initState().

main.dart

We changed the constructor arguments of the CalculationBloc (by adding calculationHistoryService) but haven’t adapted the caller yet.

The problem: we can’t just do it like this:

Scaffold(
  body: BlocProvider(
    create: (context) {
      return CalculationBloc(
        calculationHistoryService: CalculationHistoryService(
          sharedPreferences: SharedPreferences.getInstance()
        )
      );
    },
    child: Calculation(),
  ),
),

That’s because SharedPreferences.getInstance() is an async function. The build-method of our app widget, however, is not asynchronous because it must return a Widget and not a Future<Widget>. Another problem is that we don’t want to execute such things in a build-method of a widget because that might be executed several times. But in fact, one instantiation of SharedPreferences is sufficient for us. Solution: performing the instantiation at the very beginning.

main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
  runApp(
    CalculatorApp(
      sharedPreferences: sharedPreferences
    )
  );
}

class CalculatorApp extends StatefulWidget {
  CalculatorApp({
    this.sharedPreferences
  });

  final SharedPreferences sharedPreferences;

  @override
  _CalculatorAppState createState() => _CalculatorAppState(
  );
}

class _CalculatorAppState extends State<CalculatorApp> {
  @override
  void initState() {
    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
      )
    );

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter basic calculator',
      home: Scaffold(
        body: BlocProvider(
          create: (context) {
            return CalculationBloc(
              calculationHistoryService: CalculationHistoryService(
                sharedPreferences: widget.sharedPreferences
              )
            );
          },
          child: Calculation(),
        ),
      ),
    );
  }
}

By making the main() function async, we enable it to execute asynchronous functions in its body. Functions like SharedPreferences.getInstance(). This requires us to execute WidgetsFlutterBinding.ensureInitialized() beforehand. We extend the app widget by a constructor argument and put that in the widget tree.

Flutter calculator with history
The final calculator displaying its history

Conclusion

Calling a service from a BLoC is not that hard. If you want to make it right, you need to inject the service into the BLoC (and also inject every dependency into the service). This has the positive side-effect of it being testable. Since BLoCs work with Streams, we can yield the service’s return values after some other states so that no parts of the application needs to wait for the execution to finish.

If you like what you’ve read, feel free to support me:

🥗Buy me a salad

Leave a Comment