Error: change the path of the translation files using EasyLocalization Flutter - 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.

Related

Flutter Widget Test gives me this error: No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

I am new to writing widget test cases in Flutter and I found very less resources on Flutter testing, When I am trying to write test cases for a module which uses Firestore and it gives following error: No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() - Error 1
MapsRepository of MapsBloc is using Firestore to get data
I tried so many examples and the following code is working but giving another error: FirebaseCoreHostApi.initializeCore PlatformException(channel-error, Unable to establish connection on channel., null, null) - Error 1 is not observed here
Test file
void main() async{
TestWidgetsFlutterBinding.ensureInitialized();
//WidgetsFlutterBinding.ensureInitialized();
setUpAll(() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
); // setupall method is eliminated Error 1
});
testWidgets('Form Widget Test', (tester) async {
await tester.pumpWidget(initApp());
await tester.pumpAndSettle();
await tester.pump(const Duration(seconds: 2));
// Create the Finders.
final stack = find.byType(Stack);
// Create the Matchers
expect(stack, findsWidgets);
});
}
Widget initApp() {
MapsRepository mapsRepository = MapsRepository();
MapsBloc mapsBloc = MapsBloc();
MyMaps myMaps = const MyMaps();
return EasyLocalization(
supportedLocales: const [Locale('en', 'US'), Locale('hi', 'IN')],
path: 'assets/translations',
fallbackLocale: const Locale('en', 'US'),
child: MultiProvider(
providers: [
BlocProvider<MapsBloc>.value(
value: mapsBloc,
child: myMaps,
),
],
child: const MyApp(),
),
);
}
What I am missing here, same structure working for other test files. Some test files are passing test cases some are throwing error
I tried printing like below
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
).whenComplete(() => print("completed init"));
This is also not working. Any working examples would be really helpful. Thank you

Mockito 'package:mocking/main.dart" can't be resolved

I am trying to follow the flutter cookbook guide for creating mockito tests. Here is the link https://docs.flutter.dev/cookbook/testing/unit/mocking.
After solving some little issues here and there with dependency conflicts I have reached a blocker I can't seem to find much information on.
When running the tests the import 'package:mocking/main.dart'; I am getting an error saying that it cannot be resolved. I am pretty new to dart, flutter, and mockito. From what I can understand this import is supposed to mock the functions from the main.dart file.
The main.dart file lives in the lib folder while the fetch_album_test.dart lives in the test folder.
I added the http(0.13.5) dependency, and the mockito(5.3.2) and build_runner(2.3.2) dev_dependency to the pubspec.yaml file and have run pub get. I also ran flutter pub run build_runner build.
I have followed the steps in the above link and also searched the web for mentions of "mocking" and "package:mocking" but I can't find anything. There are examples of building mock tests within the same .dart file as the class but I find that it would be helpful to keep the tests separate.
So what are my questions?
Why is the import 'package:mocking/main.dart'; not found?
Can this be resolved?
Is there a better solution?
The code is the same as the Flutter docs link but here it is again so you don't have to link.
lib/main.dart
`
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum(http.Client client) async {
final response = await client
.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class Album {
final int userId;
final int id;
final String title;
const Album({required this.userId, required this.id, required this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late final Future<Album> futureAlbum;
#override
void initState() {
super.initState();
futureAlbum = fetchAlbum(http.Client());
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.title);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
),
);
}
}
`
test/fetch_album_test.dart
`
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:mocking/main.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'fetch_album_test.mocks.dart';
// Generate a MockClient using the Mockito package.
// Create new instances of this class in each test.
#GenerateMocks([http.Client])
void main() {
group('fetchAlbum', () {
test('returns an Album if the http call completes successfully', () async {
final client = MockClient();
// Use Mockito to return a successful response when it calls the
// provided http.Client.
when(client
.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1')))
.thenAnswer((_) async =>
http.Response('{"userId": 1, "id": 2, "title": "mock"}', 200));
expect(await fetchAlbum(client), isA<Album>());
});
test('throws an exception if the http call completes with an error', () {
final client = MockClient();
// Use Mockito to return an unsuccessful response when it calls the
// provided http.Client.
when(client
.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1')))
.thenAnswer((_) async => http.Response('Not Found', 404));
expect((client), throwsException);
});
});
}
`
I have tried moving around the files, and changing the import package name and I have done a lot of searching online.

How to implement App Tracking Transparency in 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

How can I download an image from the network and save it in a locally directory?

I'm trying to download an image from the network and save it locally in the Downloads folder of a computer. I need to achieve that for flutter web, I'm not sure how to do it.
I found some questions related to how to achieve download and save a file or an image for android and IOS, such as Flutter save a network image to local directory. I also took a look at How do I read and write image file locally for Flutter Web?. However, I don't see how those answers can help me.
I think that for IOS and Flutter I can use the following function without getting any error, but I don't know where the files are being saved in my emulator:
void _downloadAndSavePhoto() async {
var response = await http.get(Uri.parse(imageUrl));
try {
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
File file = File('$tempPath/$name.jpeg');
file.writeAsBytesSync(response.bodyBytes);
} catch (e) {
print(e.toString());
}
}
However, when I try the above function for flutter web (using a chrome simulator) I get the following error:
MissingPluginException(No implementation found for method getTemporaryDirectory on channel plugins.flutter.io/path_provider)
I will be more than happy if someone knows a way to do it or have some suggestions to implement that functionality.
Thanks in advance!
To achieve this I would suggest you first to add the universal_html package to your pubspec.yaml because in the newer versions of Flutter you will get warnings for importing dart:html.
In pubspec.yaml:
dependencies:
flutter:
sdk: flutter
http: ^0.13.1 // add http
universal_html: ^2.0.8 // add universal_html
I created a fully working example Flutter web app, you can try it, but the only thing that interests you is the downloadImage function.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// if you don't add universal_html to your dependencies you should
// write import 'dart:html' as html; instead
import 'package:universal_html/html.dart' as html;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final imageUrls = <String>[
'https://images.pexels.com/photos/208745/pexels-photo-208745.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
'https://images.pexels.com/photos/1470707/pexels-photo-1470707.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
'https://images.pexels.com/photos/2671089/pexels-photo-2671089.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
'https://images.pexels.com/photos/2670273/pexels-photo-2670273.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: GridView.count(
crossAxisCount: 3,
children: imageUrls
.map(
(imageUrl) => ImageCard(imageUrl: imageUrl),
)
.toList(),
),
);
}
}
class ImageCard extends StatefulWidget {
#override
_ImageCardState createState() => _ImageCardState();
final String imageUrl;
ImageCard({
#required this.imageUrl,
});
}
class _ImageCardState extends State<ImageCard> {
Future<void> downloadImage(String imageUrl) async {
try {
// first we make a request to the url like you did
// in the android and ios version
final http.Response r = await http.get(
Uri.parse(imageUrl),
);
// we get the bytes from the body
final data = r.bodyBytes;
// and encode them to base64
final base64data = base64Encode(data);
// then we create and AnchorElement with the html package
final a = html.AnchorElement(href: 'data:image/jpeg;base64,$base64data');
// set the name of the file we want the image to get
// downloaded to
a.download = 'download.jpg';
// and we click the AnchorElement which downloads the image
a.click();
// finally we remove the AnchorElement
a.remove();
} catch (e) {
print(e);
}
}
#override
Widget build(BuildContext context) {
return InkWell(
onTap: () => downloadImage(widget.imageUrl),
child: Card(
child: Image.network(
widget.imageUrl,
fit: BoxFit.cover,
),
),
);
}
}

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.