Bloc: on v5 how can create Singleton pattern Bloc class ?

Created on 20 Jul 2020  路  2Comments  路  Source: felangel/bloc

hello again dear @felangel
thank you for new release of bloc

on migration from v4 to v5 i have one problem on Bloc classes with Singleton pattern

Before:

class SingletonBloc extends Bloc<SingletonEvent, int> {

  SingletonBloc._internal();

  static final SingletonBloc _instance = SingletonBloc._internal();

  factory SingletonBloc() {
    return _instance;
  }

 @override
  int get initialState => 0;

}

After:

class SingletonBloc extends Bloc<SingletonEvent, int> {

  SingletonBloc._internal();

  static final SingletonBloc _instance = SingletonBloc._internal();

  factory SingletonBloc() {
    return _instance;
  }

   SingletonBloc() : super(0);

}

This new style of v5 interferes with factory method

are you have any solution or idea ?

thank you

question

Most helpful comment

You should remove the public constructor and simply call super(0) in SingletonBloc._internal().

class SingletonBloc extends Bloc<SingletonEvent, int> {

  SingletonBloc._internal() : super(0);

  static final SingletonBloc _instance = SingletonBloc._internal();

  factory SingletonBloc() {
    return _instance;
  }
}

All 2 comments

You should remove the public constructor and simply call super(0) in SingletonBloc._internal().

class SingletonBloc extends Bloc<SingletonEvent, int> {

  SingletonBloc._internal() : super(0);

  static final SingletonBloc _instance = SingletonBloc._internal();

  factory SingletonBloc() {
    return _instance;
  }
}

Hi @kiaxseventh 馃憢
Thanks for opening an issue!

As @Jomik mentioned you can call super now with the initial state rather than overriding the old initialState getter. Check out the migration guide for more details 馃憤

Was this page helpful?
0 / 5 - 0 ratings