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

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

Related

GetIt package - Object/factory not registered inside GetIt

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());

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

How can I call an Encrypted Hive Box to a class?

I am needing to encrypt a hive box, in which the box 'user_api' is to be called in Api_Page_() to receive user input to store inside said box. However, the encryptedBox is not defined within the class. The Hive Docs display the encryption code is to be done inside of the main() function, which I have done, but I am unsure of how to take the box outside of main().
Any help or advice is greatly appreciated!
My Code:
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
// HIVE ENCRYPTION----------------------------------------
const secureStorage = FlutterSecureStorage();
final encryptionKey = await secureStorage.read(key: 'key');
if (encryptionKey == null) {
final key = Hive.generateSecureKey();
await secureStorage.write(
key: 'key',
value: base64Encode(key),
);
}
final key = await secureStorage.read(key: 'key');
final encryptKey = base64Url.decode(key);
print('Encryption key: $encryptKey');
// HIVE ENCRYPTION----------------------------------------
// HIVE INIT---------------------------------------------
Directory directory = await getApplicationDocumentsDirectory();
Hive.init(directory.path);
await Hive.initFlutter();
final encryptedBox = Hive.openBox<String>('user_api', encryptionCipher: HiveAesCipher(encryptKey)); // Initially Opens Box on App Start
// HIVE INIT---------------------------------------------
runApp(myApp());
}
class myApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false, // Removes Debug Banner. [Delete before app release]
title: 'App Title Placeholder',
home: API_Page_() // Calls API_Page_ class from api_page.dart
);
}
}
class API_Page_ extends StatelessWidget {
const API_Page_({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: RaisedButton(onPressed: () { var eBox = encryptedBox<String>('user_api');
},
)
);
}
}

The argument type 'Future<SharedPreferences>' can't be assigned to the parameter type 'SharedPreferences'

I want to access the shared preferences at the application startup and want to use this same object across the entire app by passing it to the classes. I am getting the following error:
The argument type 'Future' can't be assigned to the
parameter type 'SharedPreferences'.
main.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:application/layouts/ScreenOne.dart';
import 'package:application/layouts/ScreenTwo.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
sharedPreferences() async {
return await SharedPreferences.getInstance();
}
final preferences = SharedPreferences.getInstance();
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MyApp',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: (preferences.getInt("login") == 1 ? ScreenOne(preferences) : ScreenTwo(preferences)),
);
}
}
I am unable to resolve this error. Is there anything I am doing wrong or missing? Thanks!!!
First of all, you defined function sharedPreferences() but did not use it later in the code - simply remove it.
Furthermore, based on the documentation SharedPreferences.getInstance() returns Future<SharedPreferences> and not SharedPreferences, hence you get the following error. You can resolve the issue by getting the SharedPreferences instance in the main method and then using constructor injection to provide the preferences object to the MyApp:
Future<void> main() async { // <-- Notice the updated return type and async
final preferences = await SharedPreferences.getInstance(); // <-- Get SharedPreferences instance
runApp(
MyApp(preferences: preferences), // <-- Inject (pass) SharedPreferences object to MyApp
);
}
class MyApp extends StatelessWidget {
final SharedPreferences preferences;
const MyApp({
required this.preferences,
})
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MyApp',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: (preferences.getInt("login") == 1 ? ScreenOne(preferences) : ScreenTwo(preferences)),
);
}
}

Provider dont update a data in Flutter

I'm create a project on Flutter. And I'm using a provider to change screens in my app.
Here is my main.dart file:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:school_app/services/auth_service.dart';
import 'package:school_app/wrapper.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => AuthService().auth,
child: MaterialApp(
home: Wrapper(),
),
);
}
}
Also this is my wrapper.dart file where the screens choose:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:school_app/screens/authenticate/auth.dart';
import 'package:school_app/models/user.dart';
import 'package:school_app/screens/school/home.dart';
import 'package:school_app/services/auth_service.dart';
class Wrapper extends StatelessWidget {
#override
Widget build(BuildContext context) {
final user = Provider.of<AuthProvider>(context);
print(user.auth);
if(!user.auth) return Auth();
return Home();
}
}
And it is my AuthProvider class:
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
class AuthService {
/* AuthUser _user(User user) {
return user != null ? AuthUser(uid: user.uid) : null;
}*/
AuthProvider auth = new AuthProvider();
//sign in
Future signIn(String username, String password) async {
try {
SharedPreferences prefs = await SharedPreferences.getInstance();
var dio = Dio();
Response user = await dio.post('url', data: {
'username': username,
'password': password
});
if(user.data['success'] == false) return user.data['msg'];
await prefs.setString('token', user.data['token']);
auth.setAuth(true);
print("SUCCESS");
} catch(e) {
print('Error ' + e.toString());
}
}
}
class AuthProvider with ChangeNotifier {
bool _auth;
AuthProvider() {
_auth = false;
}
bool get auth => _auth;
void setAuth(bool auth) {
_auth = auth;
notifyListeners();
}
}
And when I call a function in AuthProvider class setAuth, nothing changed. Can you help me and find my mistake?
EDIT
I'm making all changes that you writes but it is not working. Here is my main.dart:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:school_app/services/auth_service.dart';
import 'package:school_app/wrapper.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => AuthProvider(),
child: MaterialApp(
home: Wrapper(),
),
);
}
}
Also wrapper.dart:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:school_app/screens/authenticate/auth.dart';
import 'package:school_app/screens/school/home.dart';
import 'package:school_app/services/auth_service.dart';
class Wrapper extends StatefulWidget {
#override
_WrapperState createState() => _WrapperState();
}
class _WrapperState extends State<Wrapper> {
#override
void initState() {
// TODO: implement initState
super.initState();
AuthService().auth;
}
#override
Widget build(BuildContext context) {
return Consumer<AuthProvider>(builder: (context, authProvider, child) {
print(authProvider.auth);
if (!authProvider.auth) {
return Auth();
} else {
return Home();
}
});
}
}
And AuthService and AuthProvider classes:
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
class AuthService {
/* AuthUser _user(User user) {
return user != null ? AuthUser(uid: user.uid) : null;
}*/
AuthProvider auth = new AuthProvider();
//sign in
Future signIn(String username, String password) async {
try {
SharedPreferences prefs = await SharedPreferences.getInstance();
var dio = Dio();
Response user = await dio.post('url', data: {
'username': username,
'password': password
});
if(user.data['success'] == false) return user.data['msg'];
await prefs.setString('token', user.data['token']);
auth.setAuth(true);
print("SUCCESS");
} catch(e) {
print('Error ' + e.toString());
}
}
}
class AuthProvider with ChangeNotifier {
bool _auth;
AuthProvider() {
_auth = false;
}
bool get auth => _auth;
void setAuth(bool auth) {
_auth = auth;
notifyListeners();
}
}
Notice, that here two classes and in AuthService I'm calling function .setAuth(true).
In your current implementation of Wrapper, you are rendering the widget once and not listening to whether the values changed. You could use Consumer as suggested above. You could also choose to watch the value for changes - like this:
class Wrapper extends StatelessWidget {
#override
Widget build(BuildContext context) {
final user = context.watch<AuthProvider>();
print(user.auth);
if(!user.auth) return Auth();
return Home();
}
}
When you use a watch or Consumer pattern, the widget will be rendered when the values of the underlying store (which is AuthProvider here) gets changed.
The only missing part here is that you never Consume the AuthProvider to listen to the notifyListeners() trigger.
The correct implementation looks like the following (I didn't try it, you may have to correct some typo errors, but you'll get the idea !)
class Wrapper extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Consumer<AuthProvider>(
builder: (context, authProvider, child) {
if (!authProvider.auth) {
return Auth();
} else {
return Home();
}
}
);
}
}
EDIT
I didn't notice you weren't injecting the right Class in your ChangeNotifierProvider. You'll also have to update your widget MyApp
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => AuthProvider(),
child: MaterialApp(
home: Wrapper(),
),
);
}
And in this case you probably should transform your Wrapper widget to a Stateful widget, and in the initState method you should call AuthService().auth.
I strongly recommend you to read the official documentation of Provider, looks like things aren't crystal clear yet in your mind
EDIT 2
You're still missing the point of the Provider library.
The goal of this lib is to provide an instance of a class to your widget tree so you don't have to re-create an instance in each widget.
Here, in AuthService class you're re-creating a AuthProvider with AuthProvider auth = new AuthProvider(); instead of referring to the existing instance created in the parent Widget.
To refer to a previously created instance, you should use Provider.of<AuthProvider>(context); in the AuthService class, or, even better, pass the instance of AuthProvider as a parameter in the signIn method.