How to implement App Tracking Transparency in Flutter - flutter

I submitted my app to apple but it got rejected because i haven't added App transparency. SO far, i have imported the dependency into pubspec.yaml and i'm confused if there is more that i need to add to my main.dart in the below code, please help
import 'dart:io';
import 'dart:ui';
import 'package:easy_localization/easy_localization.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hive/hive.dart';
import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:path_provider/path_provider.dart';
import 'app.dart';
import 'models/constants.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final TrackingStatus status =
await AppTrackingTransparency.requestTrackingAuthorization();
await EasyLocalization.ensureInitialized();
await Firebase.initializeApp();
Directory directory = await getApplicationDocumentsDirectory();
Hive.init(directory.path);
await Hive.openBox(Constants.bookmarkTag);
await Hive.openBox(Constants.resentSearchTag);
await Hive.openBox(Constants.notificationTag);
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.dark));
runApp(
EasyLocalization(
supportedLocales: [Locale('en'), Locale('ar'), Locale('es')],
path: 'assets/translations',
fallbackLocale: Locale('en'),
//Defaut language
startLocale: Locale('en'),
useOnlyLangCode: true,
child: MyApp(),
)
);
}

Yes. For iOs you need to specify a key in the Info.plist.
Open file app/ios/Runner/Info.plist
and add the following line:
NSUserTrackingUsageDescription
This identifier will be used to deliver personalized ads to you.
As it is specified in the package:
https://pub.dev/packages/app_tracking_transparency

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

error in MemoryImage not defined in package pdf/widgets.dart

import 'dart:io';
import 'package:flutter/material.dart' as material ;
import 'package:flutter/services.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
class PdfParagraphApi {
static Future<void> generate(key) async {
final pdf = pw.Document();
final img = pw.MemoryImage(await rootBundle.load('assets/img.png')).buffer.asUint8List();
pdf.addPage(
pw.MultiPage(
build: (context) => <pw.Widget>[
pw.Image(img),
]),
);
}
}
i'm trying to create a pdf with an image inside it and i'm using the library pdf/widgets.dart to create the image as i found in flutters documentation but i'm facing a problem.
the error message is the following :
The function 'MemoryImage' isn't defined.
Try importing the library that defines 'MemoryImage', correcting the name to the name of an existing function, or defining a function named 'MemoryImage'.dartundefined_function
insert image into pdf not working
Replace pw.MemoryImage with material.MemoryImage, because MemoryImage comes from the painting library, which is included inside the material library.
Try to replace the below import:
import 'package:flutter/material.dart' as material ;
with this import 'package:flutter/material.dart';
Try this below way:
Imports you need
import 'package:flutter/material.dart';
import 'dart:math';
import 'dart:typed_data';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart ' as pw;
import 'dart:io';
import 'package:permission_handler/permission_handler.dart';
and in the top you need to define the image you want to print _imageFile = someImage:
Uint8List? _imageFile ;
Then this is the function to make an image to pdf and save it in the Downloads Folder
Future getPdf() async {
var random = Random();
var uniqueNum = random.nextInt(99999);
//get storage permission
Map<Permission, PermissionStatus> storagePermission = await [
Permission.storage,
].request();
pw.Document pdf = pw.Document();
pdf.addPage(
pw.Page(
pageFormat: PdfPageFormat.a4,
build: (context) {
return pw.Expanded(
child: pw.Image(pw.MemoryImage(_imageFile), fit: pw.BoxFit.contain),
);
},
),
);
String path = await ExternalPath.getExternalStoragePublicDirectory(
ExternalPath.DIRECTORY_DOWNLOADS);
String mainPath = "$path/Report$uniqueNum.pdf";
File pdfFile = File(mainPath);
pdfFile.writeAsBytesSync(await pdf.save());
}

Error: change the path of the translation files using EasyLocalization Flutter

I´m new using flutter and I'm trying to implement EasyLocalization in my project, I have two project, one for the json files and other to the app, but I don't know how I can set the path to recognize the files hosted in the project of the traslations. Below my code:
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:jarvis_ui/jarvis_ui.dart';
import './src/ui/view/view.dart';
import 'idle.dart';
import 'src/ui/ui.dart';
import 'src/ui/view/error/error.dart';
Future<void> main() async {
String defaultRoute = window.defaultRouteName;
Uri _uri = Uri.parse(defaultRoute);
WidgetsFlutterBinding.ensureInitialized();
await EasyLocalization.ensureInitialized();
await SystemChrome.setPreferredOrientations(
<DeviceOrientation>[
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
],
);
runApp(
EasyLocalization(
supportedLocales: <Locale>[
Locale('es', 'CL'),
Locale('es', 'CO'),
Locale('es', 'PE'),
],
fallbackLocale: Locale('es', 'CL'),
path: 'packages/ui_shared/assets/languages',
assetLoader: RootBundleAssetLoader(),
child: ProviderScope(
observers: <ProviderObserver>[
// Logger(),
],
child: MyApp(params: _uri.queryParameters),
),
),
);
}
class MyApp extends HookWidget {
const MyApp({required this.params});
final Map<String, dynamic> params;
#override
Widget build(BuildContext context) => IdleApp(params: params);
}
In import 'package:jarvis_ui/jarvis_ui.dart'; is hosted the json files for the traslations. Then, I think that the correct way to assign the path was: path: 'packages/ui_shared/assets/languages', but I was wrong. The error is here:
In the pubspec.yaml of project that I have the json files stored, I have this:
flutter:
assets:
- assets/languages/
Thank you so much if you can help me with this.

How do I initialize Firebase App in Flutter widget testing

So I am new in flutter and trying to perform widget testing on my app, but I am keep getting this weird error.
below is my test file
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:folk_team_app/provider/auth_provider.dart';
import 'package:folk_team_app/screens/phone_login.dart';
import 'package:provider/provider.dart';
void main() async {
TestWidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
Widget loginScreen = ChangeNotifierProvider<AuthProvider>(
create: (context) => AuthProvider(),
builder: (context, child) {
return MaterialApp(
home: PhoneLogineScreen(),
);
});
testWidgets('Phone Authetication Page', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(loginScreen);
await tester.pump(const Duration(seconds: 10));
final titleText = find.text('Screen Title');
// Verify that our counter starts at 0.
expect(titleTextt, findsOneWidget);
});
}
here is the error :
You can't directly test Firebase because it requires platform configurations in order to initialize it properly.
You need to mock Firebase in the test environment using mockito.
You may find this comment and tutorial video helpful.