GetIt package - Object/factory not registered inside GetIt - flutter

I am using the GetIt package in my Flutter project to manage dependencies. However, I'm facing an issue where the package is throwing an _AssertionError with the following message:
'package:get_it/get_it_impl.dart': Failed assertion: line 372 pos 7:
'instanceFactory != null': Object/factory with type Client 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?)
I have tried to await the initialization of the dependencies inside the main function before running the app, but the error persists. I have no clue how to debug this issue.
Can anyone please guide me on how to resolve this error and properly register my dependencies with GetIt? Any help would be appreciated. Thank you.
dependencies:
bloc: ^8.1.1
flutter_bloc: ^8.1.2
get_it: ^7.2.0
code:
//main.dart
import 'package:bloc_app/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'home_feature/home_screen.dart';
import 'home_feature/application/bloc/api_request_bloc.dart';
import 'package:bloc_app/injection.dart' as di;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await di.init();
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(
theme: AppTheme.ligthTheme,
darkTheme: AppTheme.darkTheme,
themeMode: ThemeMode.system,
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: BlocProvider(
create: (context) => di.sl<ApiRequestBloc>(),
child: const MyHomePage(title: 'Bloc App'),
),
);
}
}
The Get_it instance is created globaly here.
//injection.dart
import 'package:bloc_app/home_feature/application/bloc/api_request_bloc.dart';
import 'package:bloc_app/home_feature/domain/repositories/advicer_repository.dart';
import 'package:bloc_app/home_feature/domain/usecases/advicer_usecases.dart';
import 'package:bloc_app/home_feature/infrastructure/datasources/advicer_remote_datasource.dart';
import 'package:bloc_app/home_feature/infrastructure/repositories/advicer_repository_impl.dart';
import 'package:get_it/get_it.dart';
import 'package:http/http.dart' as http;
final sl = GetIt.instance;
Future<void> init() async {
// Blocs
sl.registerFactory(() => ApiRequestBloc(usecases: sl()));
//Usecases
sl.registerLazySingleton(() => AdvicerUseCases(advicerRepository: sl()));
//Repositories
sl.registerLazySingleton<AdvicerRepository>(
() => AdvicerRepositoryImpl(advicerRemoteDataSource: sl()));
//Datasources
sl.registerLazySingleton<AdvicerRemoteDataSource>(
() => AdvicerRemoteDataSourceImpl(client: sl()));
//Extern
sl.registerLazySingleton(() => http.Client);
}
The used bloc that get used inside the main.dart
//api_request_bloc.dart
import 'package:bloc/bloc.dart';
import 'package:bloc_app/home_feature/domain/entities/advice_entity.dart';
import 'package:bloc_app/home_feature/domain/failures/failures.dart';
import 'package:bloc_app/home_feature/domain/usecases/advicer_usecases.dart';
import 'package:dartz/dartz.dart';
// ignore: depend_on_referenced_packages
import 'package:meta/meta.dart';
part './api_request_event.dart';
part './api_request_state.dart';
class ApiRequestBloc extends Bloc<ApiRequestEvent, ApiRequestState> {
final AdvicerUseCases usecases;
ApiRequestBloc({required this.usecases}) : super(ApiRequestInitial()) {
on<ApiRequestEvent>((event, emit) async {
emit(ApiRequestLoading());
Either<AdviceEntity, Failure> adviceOrFailure =
await usecases.getAdviceUsecase();
//If usecase gives error than state retunres falure otherwise the advice get shown
adviceOrFailure.fold(
(advice) => emit(ApiRequestLoaded(advice: advice.advice)),
(failure) => emit(ApiRequestError(
error: _mapFailureToError(failure),
)),
);
});
}
String _mapFailureToError(Failure failure) {
switch (failure.runtimeType) {
case ServerFailure:
return 'Error: ${failure.runtimeType} ~ could not communicate with the server.';
case GeneralFailure:
return 'Error: ${failure.runtimeType} ~ Could not define error.';
default:
return 'Error: ${failure.runtimeType} ~ Could not define error.';
}
}
}

You are missing () while registering http.Client in file injection.dart
//Extern
sl.registerLazySingleton(() => http.Client());

Related

Unhandled Exception: Could not connect to 127.0.0.1:28015. Error SocketException: Connection refused (OS Error: Connection refused, errno = 111)

i am Trying to connect my flutter chat app with Docker server (Rethinkdb) but the error on top is Showing
Here is my CompositionRoot.dart :
import 'package:chat/chat.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_newapp/src/blocs/onBoarding/onboarding_cubit.dart';
import 'package:flutter_newapp/src/blocs/onBoarding/prfil_image_cubit.dart';
import 'package:flutter_newapp/src/data/Services/image_uploader.dart';
import 'package:flutter_newapp/src/data/Services/local_cache.dart';
import 'package:flutter_newapp/src/presentation/screen/onBoarding/onboarding.dart';
import 'package:rethink_db_ns/rethink_db_ns.dart';
import 'package:shared_preferences/shared_preferences.dart';
class CompositionRoot {
static late SharedPreferences _sharedPreferences;
static late RethinkDb _r;
static late Connection _connection;
static late IUserService _userService;
static late ILocalCache _localCache;
static late ImageUploader imageUploader;
static configure() async {
_r = RethinkDb();
_connection = await _r.connect(host: "127.0.0.1", port: 28015);
_userService = UserService(_r, _connection);
_localCache = LocalCache(_sharedPreferences);
}
static Widget composeOnboardingUi() {
ImageUploader imageUploader = ImageUploader('http://localhost:3000/upload');
OnBoardingCubit onboardingCubit =
OnBoardingCubit(_userService, _localCache, imageUploader);
return MultiBlocProvider(providers:[
BlocProvider(create: (BuildContext context) => onboardingCubit ),
BlocProvider(create: (BuildContext context) => ProfileImageCubit() )
], child: OnBoardingScreen());
}
}
and here are muy main.dart file :
import 'package:flutter/material.dart';
import 'package:flutter_newapp/core/app_theme.dart';
import 'package:flutter_newapp/src/presentation/screen/onBoarding/onboarding.dart';
import 'composition_root.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await CompositionRoot.configure();
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: 'Chat App',
debugShowCheckedModeBanner: false,
theme: lightTheme(context),
darkTheme: darkTheme(context),
home: CompositionRoot.composeOnboardingUi(),
);
}
}
and the rethinkdb is already running as you see :
i Tried to change the 127.0.0.1 by my Machine's ip addresse but the same problem is still showing

Google OAuth 2.0 failing with Error 400: invalid_request for some client_id, Can't Sign in because 'App' sent an invalid request

I have an Flutter app that uses googleapis_auth 1.3.1 and googleapis 9.2.0 .
What I have done:
enabled the Google Calender API
connect Flutter Project to Firebase
and set up with basic template.
But I am getting the following error:
Here is my code:
`
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:googleapis/calendar/v3.dart' as cal;
import 'package:url_launcher/url_launcher.dart';
import 'gCalender/calendar_client.dart';
import 'secert.dart';
import 'package:googleapis_auth/auth_io.dart';
void main() async {
//firebase initialize
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
//google apis init
var clientID = ClientId(Secret.getId(),"");
var scopes = [cal.CalendarApi.calendarEventsScope];
await clientViaUserConsent(clientID, scopes, prompt).then((AuthClient client) async {
CalendarClient.calendar = cal.CalendarApi(client);
});
runApp(const MyApp());
}
void prompt(String url) async {
if (!await launchUrl(Uri.parse(url))) {
throw 'Could not launch $url';
}
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Social Login',
theme: theme(),
debugShowCheckedModeBanner: false,
initialRoute: SplashScreen.routeName,
// home: const SplashScreen(),
routes: routes,
);
}
}
`
I explored the internet but couldn't find any solution.
if you use emulator, try the app in real phone, cuz some times firebase services not working well in the virtual phones

Flutter Unit Class with Initializer

I'm trying to write the unit test for this class, but I'm having problems about the initializer... When I instantiate the class in the test file, the caller throws an error that " Null check operator used on a null value". I know that's because the UserProvider is not initialized on the test folders. But how can I mock this??
class ContactController extends ChangeNotifier {
BuildContext context;
ContactController(this.context) {
initializeData();
}
late Contact contact;
initializeData() {
var userProvider = context.read<UserProvider>();
var currentContact = userProvider?.contact;
if (currentContact != null) {
newContact = currentContact;
}
notifyListeners();
}
}
The code below should do the trick. The thing is that you need to provide a mocked UserProvider into the context. To do so, just use MultiProvider in the tests to inject the mocked one.
Note the use of #GenerateMocks([UserProvider]). This comes from mockito and it annotates the source to generate the MockUserProvider class. And to generate the *.mocks.dart just run flutter pub run build_runner build.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:provider/provider.dart';
import 'package:so72756235_test_provider/contact_controller.dart';
import 'contact_controller_test.mocks.dart';
#GenerateMocks([UserProvider])
void main() {
testWidgets('ContactController test', (WidgetTester tester) async {
final mockUserProvider = MockUserProvider();
when(mockUserProvider.contact).thenReturn(const Contact(name: 'Test'));
await tester.pumpWidget(
MultiProvider(
providers: [
Provider<UserProvider>(create: (_) => mockUserProvider),
ChangeNotifierProvider(
create: (context) => ContactController(context)),
],
child: Consumer<ContactController>(
builder: (context, value, child) =>
Text(value.newContact.name, textDirection: TextDirection.ltr)),
),
);
expect(find.text('Test'), findsOneWidget);
});
}

Flutter - auto_route _CustomNavigatorState error

I'm using the auto_route package in order to route my app and until 2 days ago everything worked just fine, until now.
For some reason, I'm getting the following error.
SYSTEM:
flutter: 1.22
dart: 2.10.0
auto_route: ^0.6.7
ERROR:
../../.pub-cache/hosted/pub.dartlang.org/custom_navigator-0.3.0/lib/custom_navigator.dart:60:7: Error: The non-abstract class '_CustomNavigatorState' is missing implementations for these members:
- WidgetsBindingObserver.didPushRouteInformation
Try to either
- provide an implementation,
- inherit an implementation from a superclass or mixin,
- mark the class as abstract, or
- provide a 'noSuchMethod' implementation.
class _CustomNavigatorState extends State<CustomNavigator>
^^^^^^^^^^^^^^^^^^^^^
/opt/flutter/packages/flutter/lib/src/widgets/binding.dart:122:16: Context: 'WidgetsBindingObserver.didPushRouteInformation' is defined here.
Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
main.dart
import 'package:device_simulator/device_simulator.dart';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'Test.gr.dart' as r;
void main() => runApp(MyApp());
const bool debugEnableDeviceSimulator = true;
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
builder: ExtendedNavigator.builder<r.Router>(
router: r.Router(),
builder: (context, extendedNav) => DeviceSimulator(
enable: debugEnableDeviceSimulator,
child:
Scaffold(body: extendedNav, backgroundColor: Colors.red ),
),
),
);
}
}
Also, I should mention, because of some update of flutter I guess, now I need to use r.Router instead of just Router.
Test.dart
import 'package:auto_route/auto_route_annotations.dart';
#MaterialAutoRouter(
routes: <AutoRoute>[],
)
class $Router {}
And also if has any importance here it's the generated file
Test.gr.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// AutoRouteGenerator
// **************************************************************************
// ignore_for_file: public_member_api_docs
import 'package:auto_route/auto_route.dart';
class Routes {
static const all = <String>{};
}
class Router extends RouterBase {
#override
List<RouteDef> get routes => _routes;
final _routes = <RouteDef>[];
#override
Map<Type, AutoRouteFactory> get pagesMap => _pagesMap;
final _pagesMap = <Type, AutoRouteFactory>{};
}
Do you have any idea what's going one here or how can I fix this? Or if I can't fix this, what can I use instead of the auto_route package which will offer me the same benefice?
i solved this problem with add some function on library CustomNavigator :
Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
return didPushRoute(routeInformation.location);
}
Find the place where the error is generating. Add the following function below there. I did the same and my problem is solved.
Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
return didPushRoute(routeInformation.location);
}

How to use same Future another .dart file? (Flutter)

I'd like to use Future teamMember() in another .dart file. Any contributions are welcome!
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';
void main() {
runApp(new MaterialApp(
home: new Popups(),
));
}
class Popups extends StatefulWidget {
#override
_PopupsState createState() => _PopupsState();
}
class _PopupsState extends State<Popups> {
Future teamMember() async {
await showDialog(
context: context,
...
...
In the other class where you need it create a reference to your popup class and then call teamMember.
class OtherClass extends StatelessWidget {
Popups _popups = Popups();
.
.
RaisedButton(
child: Text("show team member popup"),
onPressed: (){
_popups.teamMember();
}
)
}
hope this helps