injectable icon indicating copy to clipboard operation
injectable copied to clipboard

injectable environments are broken

Open stalinkay opened this issue 7 months ago • 9 comments

Greetings, @Milad-Akarie!

I just discovered injectable. Love it, but I can't use environments. If I remove environments, everything works fine. I have tried to get it to work for the past 3 days but no luck. I believe the package breaks when newer Flutter and/or Dart. Or am I doing something wrong?

Creating a new Flutter project with the latest injectable and get_it versions results in the following error:

$ flutter run

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Bad state: GetIt: Object/factory with type ConcreteTest is not registered inside GetIt.
(Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;
Did you forget to register it?)
#0      throwIfNot (package:get_it/get_it_impl.dart:12:19)
#1      _GetItImplementation._findFactoryByNameAndType (package:get_it/get_it_impl.dart:396:5)
#2      _GetItImplementation.get (package:get_it/get_it_impl.dart:424:29)
#3      _GetItImplementation.call (package:get_it/get_it_impl.dart:464:12)
#4      main (package:injectable_environments/main.dart:9:8)
#5      _runMain.<anonymous closure> (dart:ui/hooks.dart:301:23)
#6      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#7      _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)

Steps to reproduce:

  1. Create a new Flutter project with flutter create injectable_environments
  2. Add flutter pub add injectable get_it
  3. Add flutter pub add build_runner injectable_generator --dev
  4. Use the code below
  5. Run dart run build_runner watch to create injectable.config.dart file
  6. Finally, run flutter run

lib/main.dart

import 'package:flutter/material.dart';
import 'package:injectable_environments/concrete_test.dart';
import 'package:injectable_environments/injectable.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  configureDependencies();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a blue toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }
 
  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    getIt<ConcreteTest>();
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

lib/test.dart

abstract class ITest {
  void pass();
}

lib/concretetest.dart

import 'package:flutter/material.dart';
import 'package:injectable/injectable.dart';
import 'package:injectable_environments/test.dart';

@Injectable(as: ITest)
@Environment("dev") // or @dev
class ConcreteTest implements ITest {
  ConcreteTest();
  @override
  void pass() {
    debugPrint("passed");
  }
}

lib/injectable.dart

import 'package:injectable_environments/injectable.config.dart';
import 'package:get_it/get_it.dart';
import 'package:injectable/injectable.dart';

final getIt = GetIt.instance;

//Define the Environments here
// const dev = Environment('dev');
// const prod = Environment('prod');

@InjectableInit(
  initializerName: r'$initGetIt', // default
  preferRelativeImports: true, // default
  asExtension: false, // default
)
void configureDependencies({Environment environment = dev}) {
  //we init the dependencies using a speciffic env
  $initGetIt(getIt);
}

Flutter environment:

Flutter 3.16.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 7f20e5d18c (3 days ago) • 2023-11-27 09:47:30 -0800
Engine • revision 22b600f240
Tools • Dart 3.2.1 • DevTools 2.28.3

stalinkay avatar Nov 30 '23 20:11 stalinkay

Injectable, LazySingleton, and Singleton annotations are also not working at all. The lowercase variants work, but only when no environment is specified.

stalinkay avatar Dec 01 '23 00:12 stalinkay

Facing the same issue, I have a big multi-package project with multiple environments Getting the following during building phase [SEVERE] injectable_generator:injectable_config_builder on lib/feature/user/data/repository/in_app_purchase_repository.dart (cached): This builder requires Dart inputs without syntax errors. This started happening after I have upgraded flutter to 3.16.1/2

Flutter Version: Flutter 3.16.2 • channel stable • https://github.com/flutter/flutter.git Framework • revision 9e1c857886 (4 days ago) • 2023-11-30 11:51:18 -0600 Engine • revision cf7a9d0800 Tools • Dart 3.2.2 • DevTools 2.28.3

mosabalrsaheed avatar Dec 04 '23 21:12 mosabalrsaheed

@stalinkay found any workarounds for this?

mosabalrsaheed avatar Dec 30 '23 07:12 mosabalrsaheed

@stalinkay found any workarounds for this?

@mosabalrsaheed

I have found very interesting quirks and inconsistencies in injectable and its docs.

I have stopped trying to use environments even though I'm somehow still passing prod to injectable.

I also figured out that in the case of subclasses that are bound to an abstract class. It's better to use getIt(instanceName: ''). This is not documented AFAIK but it showed up in my generated injectable.config.dart

Example of AnalyticsService subclasses:

AnalyticsService branchServicce =
        getIt(instanceName: 'BranchAnalyticsService');
AnalyticsService oneSignalService =
        getIt(instanceName: 'OneSignalAnalyticsService');

It's not possible to annotate abstract classes unless they are base/abstract classes.

One last thing: I've also picked up cases where changing the annotation from to @injectable works but @lazySingleton would through an error when generating the injectable.config.dart. Can't remember the exact issue there but it's something along that line.

I'll attempt to use environments again once my code base is stable.

stalinkay avatar Dec 31 '23 23:12 stalinkay

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions

github-actions[bot] avatar Jan 31 '24 08:01 github-actions[bot]

I have this same issue. Seems there is a PR (#408, ping @Milad-Akarie ) with a fix that has not yet been merged.

FelixZY avatar Feb 04 '24 16:02 FelixZY

EDIT

The fix has now been merged and this comment is therefore outdated.


I have now confirmed that the fix in #408 works for me and set up a fork that can be used as a workaround until the PR is merged. The fork was necessary as injectable_generator has a relative dependency on injectable in @lrampazzo 's branch. Relative dependencies are not supported when referencing remote git repositories and so I had to update this dependency.

To use the fix for #408 before it has been merged, update your pubspec.yaml:

dependencies:
#  injectable: ^2.3.2
  injectable:
    git:
      url: https://github.com/FelixZY/injectable.git
      path: injectable
      ref: fix-singleton-environment-filter

dev_dependencies:
#  injectable_generator: ^2.4.1
  injectable_generator:
    git:
      url: https://github.com/FelixZY/injectable.git
      path: injectable_generator
      ref: fix-singleton-environment-filter

FelixZY avatar Feb 04 '24 16:02 FelixZY

Hi @FelixZY,

I checked out your repo, but the issue persists. I believe the root cause might be an incorrect order of injectable registration.

According to the official documentation, injectable are reordered based on their dependencies. In other words, if A depends on B, B should be registered first. However, in the current version, B seems to be registered after A. Consequently, when get_it tries to create a new instance of A, it cannot find B, leading to the issue happened.

cogivn avatar Feb 23 '24 08:02 cogivn

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions

github-actions[bot] avatar Apr 06 '24 08:04 github-actions[bot]