flutterdartblocinjectable

Performance with injectable, get_it Flutter


I have a question. In my project, I have some class with singleton.

and init all at $initGetIt the same.

_i1.GetIt $initGetIt(_i1.GetIt get,
    {String? environment, _i2.EnvironmentFilter? environmentFilter}) {
  final gh = _i2.GetItHelper(get, environment, environmentFilter);
  gh.singleton<_i3.DioConfig>(_i3.DioConfig());
  gh.singleton<_i4.DioMethod>(_i4.DioMethod(get<_i3.DioConfig>()));
  gh.singleton<_i5.MovieApiProvider>(
      _i5.MovieApiProvider(get<_i4.DioMethod>()));
  gh.singleton<_i6.Repository>(_i6.Repository());
  gh.lazySingleton<_i7.MovieDetailBloc>(
      () => _i7.MovieDetailBloc(get<_i6.Repository>()),
      dispose: (i) => i.dispose());
  gh.lazySingleton<_i8.MoviesBloc>(() => _i8.MoviesBloc(get<_i6.Repository>()),
      dispose: (i) => i.dispose());
  return get;
}

I think If I scale my project, I can get some problem.

  1. This function will be too large and we have too much singleton still live in app.
  2. We need to init a lot of Object when opening the app => Can delay app?
  3. How to create a singleton only alive when access to the screen and destroyed after pop this screen.

Thank you for your anwser!


Solution

  • This function will be too large and we have too much singleton still live in app.

    I have hundreds of GetIt singletons and I do not see any problems.

    We need to init a lot of Object when opening the app => Can delay app?

    If you are worried about number of Objects - do not need to worry. When Flutter builds a frame (you know, it builds 60 frames per second), it creates a huge widget tree contains thousands of widgets and each widget contains dozens of objects. So hundreds of objects are really a very small number. Dart's Garbage Collector is designed for the many-object case.

    How to create a singleton only alive when access to the screen and destroyed after pop this screen.

    class MyPageOne extends StatefulWidget {
      const MyPageOne({Key? key}) : super(key: key);
    
      @override
      _MyPageOneState createState() => _MyPageOneState();
    }
    
    class _MyPageOneState extends State<MyPageOne> {
      @override
      void initState() {
        super.initState();
        GetIt.I.registerSingleton<MyClass>(MyClass());
      }
      
      @override
      void dispose() {
        GetIt.I.unregister<MyClass>();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return ...your page...;
      }
    }
    

    This is just an example and you can, for example, encapsulate it into a widget.