freezed package can not generate toJson code for nested object anymore - flutter

We've discovered an issue in our monorepo that prevents us from generating .g.dart files for our models. Most of the models are deeply nested and need fromJson/toJson methods to communicate with our backend. Three weeks ago we updated freezed and the whole build_runnerc/code-generator setup. We changed the following versions:
json_annotation: ^4.6.0 => ^4.7.0
json_serializable: ^6.3.1 => ^6.5.3
build_runner: ^2.1.10 => ^2.3.2
freezed: ^2.1.0+1 => ^2.2.0
freezed_annotation: ^2.0.0=> ^2.2.0
A couple of days ago we got this error message running build_runner:
[SEVERE] json_serializable on lib/src/entities/user/user_banking_info.dart (cached):
Could not generate `toJson` code for `documents` because of type `UserDocument`.
package:common/src/entities/user/user_banking_info.freezed.dart:109:26
╷
109 │ List<UserDocument> get documents {
│
In other packages of our monorepo we are getting the error message that the .g.dart file hasn't been generated:
Target of URI hasn't been generated: ''fetch_articles_response.g.dart''.
Try running the generator that will generate the file referenced by the URI.
Flutter and Dart versions used:
Flutter version: 3.3.7
Dart SDK version: 2.18.4
pubspec.yaml of articles package, same versions are used in the common package:
name: article
version: 0.0.1
publish_to: none
environment:
sdk: ">=2.17.0 <3.0.0"
dependencies:
common:
path: ../common
freezed_annotation: ^2.2.0
json_annotation: ^4.7.0
dev_dependencies:
build_runner: ^2.1.10
freezed: ^2.1.0+1
json_serializable: ^6.3.1
user.dart
import 'package:common/common.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'user.freezed.dart';
part 'user.g.dart';
#freezed
class User with _$User {
const User._();
const factory User({
UserBankingInfo? banking_info,
}) = _User;
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
}
user_banking_info.dart
import 'package:common/src/entities/user/user_document.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'user_banking_info.freezed.dart';
part 'user_banking_info.g.dart';
#freezed
class UserBankingInfo with _$UserBankingInfo {
const factory UserBankingInfo({
#Default([]) List<UserDocument> documents,
}) = _UserBankingInfo;
factory UserBankingInfo.fromJson(Map<String, dynamic> json) => _$UserBankingInfoFromJson(json);
}
user_document.dart
import 'package:freezed_annotation/freezed_annotation.dart';
part 'user_document.freezed.dart';
part 'user_document.g.dart';
#freezed
class UserDocument with _$UserDocument {
const factory UserDocument({
String? id,
}) = _UserDocument;
factory UserDocument.fromJson(Map<String, dynamic> json) => _$UserDocumentFromJson(json);
}
It feels like I've tried every version or combination of package versions needed for this to work and I can't figure out where this issue is coming from. Right now I downgraded all package versions in our application to match the versions that worked before. Every package used by freezed exist in each package of the monorepo. I'm also forced to use json_annotation: ^4.7.0 due to version constraints (The version constraint "^4.6.0" on json_annotation allows versions before 4.7.0 which is not allowed.).
After reading the freezed documentation again I've also added
errors:
invalid_annotation_target: ignore
to our analysis_options.yaml and
targets:
$default:
builders:
json_serializable:
options:
explicit_to_json: true
to the build.yaml in each package.
I've also tested this with the newest versions of each package but without success. Downgrading my Flutter SDK didn't help either.

This issue has been solved thanks to #SunlightBro by using:
dependency_overrides:
freezed: 2.1.0
in all packages of the application because other dependencies used by the application restricted the use of analyzer to version 4.7.0 instead of 5.2.0 which was required by freezed. I was able to find this restriction by running dart pub deps.

Related

Unable to generate g.dart with retrofit flutter

I am migrating my flutter project to 3.3.0 and i am calling API with retrofit which was working fine, after upgrading all packages i delete .g.dart file and run the following command to rebuild the .g.dart file
flutter pub run build_runner build it thrown the following error.
Error: No named parameter with the name 'autoCastResponse'.
autoCastResponse: annotation?.peek('autoCastResponse')?.boolValue,
^^^^^^^^^^^^^^^^
/E:/ahmad/Android/Android%20Bundle%20Setup/flutter/.pub-cache/hosted/pub.dartlang.org/retrofit-3.3.0/lib/http.dart:66:9: Context: Found this candidate, but th
e arguments don't match.
const RestApi({
^^^^^^^
/E:/ahmad/Android/Android%20Bundle%20Setup/flutter/.pub-cache/hosted/pub.dartlang.org/retrofit_generator-4.1.2/lib/src/generator.dart:494:27: Error: The getter 'autoCastResponse' isn't defined for the class 'RestApi'.
- 'RestApi' is from 'package:retrofit/http.dart' ('/E:/ahmad/Android/Android%20Bundle%20Setup/flutter/.pubcache/hosted/pub.dartlang.org/retrofit-3.3.0/lib/http.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'autoCastResponse'.
(clientAnnotation.autoCastResponse ?? true);
^^^^^^^^^^^^^^^^
[INFO] Precompiling build script... completed, took 900ms
[SEVERE] Failed to precompile build script .dart_tool/build/entrypoint/build.dart.
This is likely caused by a misconfigured builder definition.
pub finished with exit code 78
I also try this command flutter packages pub run build_runner build --delete-conflicting-outputs
But the result remains the same.
Here is how my abstract class looks like,
part 'rest_client.g.dart';
#RestApi(baseUrl: "https://myapi.com/")
abstract class RestClient {
factory RestClient(Dio dio, {String baseUrl}) = _RestClient;
#POST("/Flag")
Future<LoginResponse> login(#Body() LoginRequest loginRequest)`;}`
These are my packages version:
retrofit: ^3.3.0
dev_dependencies:
flutter_test:
sdk: flutter
retrofit_generator: ^4.1.2
build_runner: ^2.2.1
json_serializable: ^6.4.1
dependency_overrides:
analyzer: '5.1.0'
According to this githubLink
retrofit: 3.3.0 had bugs and the author forgot to publish the generator accordingly. So after resolving that bug using retrofit: ^3.3.1 and retrofit_generator: 4.2.0 is working fine
You will need to upgrade the package retrofit_generator to 4.2.0
you need to take care of the file naming your file name should be like what you will generate if you will generate [users.g.dart] your file name should be [ users.dart] or it will not create the file
and also upgrade your package to retrofit_generator: ^4.0.3+1

package is forbidden but only when it's imported

Here's an error I'm getting when trying to save the pubspec.yaml (which automatically runs flutter pub get) (I changed the names of the packages):
Running "flutter pub get" in ravencoin_front...
Because every version of package_b from path depends on
package_c any which is forbidden, package_b from path is
forbidden. So, because package_a depends on package_b from
path, version solving failed. pub get failed (server unavailable) --
attempting retry 1 in 1 seconds...
So the question is, why is package_c forbidden? Here's what package_c looks like:
pubspec.yaml:
name: package_c
version: 1.0.0
description: Serverpod client for communication to the consent server and database.
homepage: https://github.com/.../package_c
environment:
sdk: '>=2.12.0 <3.0.0'
dependencies:
serverpod_client: ^0.9.8
/lib/package_c.dart
library package_c;
export 'package:package_c/src/protocol/protocol.dart';
export 'package:serverpod_client/serverpod_client.dart';
Finally here's protocol.dart:
/* AUTOMATICALLY GENERATED CODE DO NOT MODIFY */
/* To generate run: "serverpod generate" */
// ignore_for_file: public_member_api_docs
// ignore_for_file: unnecessary_import
library protocol;
// ignore: unused_import
import 'dart:typed_data';
import 'package:serverpod_client/serverpod_client.dart';
import 'consent_class.dart';
import 'consent_document_class.dart';
export 'consent_class.dart';
export 'consent_document_class.dart';
export 'client.dart';
class Protocol extends SerializationManager {
static final Protocol instance = Protocol();
final Map<String, constructor> _constructors = {};
#override
Map<String, constructor> get constructors => _constructors;
Protocol() {
constructors['Consent'] = (Map<String, dynamic> serialization) =>
Consent.fromSerialization(serialization);
constructors['ConsentDocument'] = (Map<String, dynamic> serialization) =>
ConsentDocument.fromSerialization(serialization);
}
}
There are no errors, not sure why this package is seen as "forbidden."
Now package_b also requires other pacakges and overrides their paths, and they work just fine. so at first I thought it doesn't like the "nested paths" part of this situation, but that's not it, otherwise it would complain about the others too.
I also wondered, maybe the issue is that it has two "library" listed in the files. but I don't think that's it because if I remove the library package_c; it has the same problem.
Maybe it's as simple as this package_c not being correctly setup as a package, but I think it is, I looked up the requirements and it seems to fit from what I found.
Just for good measure let me include some of package_b pubspect.yaml:
name: package_b
description: Ravencoin wallet backend library
version: 1.0.0
environment:
sdk: '>=2.12.0 <3.0.0'
dependencies:
...
package_d: ^4.0.1
...
package_c: ^1.0.0
dependency_overrides:
# causes error!
package_c:
path: ../../package_c
# works fine!
package_d:
path: ../../package_d
...
Now, Here's the really weird part. remember, package_a imports pacakge_b which imports package_c. Well, package_b works just fine, dart pub get works great. but when I run flutter pub get in package_a, the error at the top occurs. the weird thing is only package_a complains about package_c, package_b is fine with package_c... what?
I guess I should include part of the pubspec.yaml for package_a too, this is the one that causes the error:
name: package_a
description: Ravencoin wallet frontend
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+0
environment:
sdk: '>=2.14.0 <3.0.0'
dependencies:
...
flutter:
sdk: flutter
package_b: ^1.0.0
...
dependency_overrides:
package_b:
path: ../package_b
...
...

The method 'watchPerformance' isn't defined for the type 'IntegrationTestWidgetsFlutterBinding'

I'm currently doing the integrated_test codelab on https://codelabs.developers.google.com/codelabs/flutter-app-testing/#6.
I'm on step 6 where I have to test the performance of the test_app:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:testing_app_codelab/main.dart';
import 'package:testing_app_codelab/testing_app.dart';
void main() {
group('Testing App Performance Tests', () {
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized()
as IntegrationTestWidgetsFlutterBinding;
binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive;
testWidgets('Scrolling test', (tester) async {
await tester.pumpWidget(TestingApp());
final listFinder = find.byType(ListView);
await binding.watchPerformance(() async { // error is here
await tester.fling(listFinder, Offset(0, -500), 10000);
await tester.pumpAndSettle();
await tester.fling(listFinder, Offset(0, 500), 10000);
await tester.pumpAndSettle();
}, reportKey: 'scrolling_summary');
});
});
}
I've gone through the IntegrationTestWidgetsFlutterBinding documentation and watchPerformance() is a method of it(please check: https://api.flutter.dev/flutter/package-integration_test_integration_test/IntegrationTestWidgetsFlutterBinding/watchPerformance.html).
The error I get on VS code is:
The method 'watchPerformance' isn't defined for the type 'IntegrationTestWidgetsFlutterBinding'.
Try correcting the name to the name of an existing method, or defining a method named 'watchPerformance'.
When I run the Integration test on my Android phone I get this error:
Try correcting the name to the name of an existing method, or defining a method named 'watchPerformance'.
await binding.watchPerformance(() async {
I got the idea to solve this problem from this post Flutter / Dart package integration_test with null safety
The problem was that integration_test dependency doesn't support null-safety.
when you check which dependencies have null safety support using this command:
dart pub outdated --mode=null-safety
The output is:
Showing dependencies that are currently not opted in to null-safety.
[✗] indicates versions without null safety support.
[✓] indicates versions opting in to null safety.
Package Name Current Upgradable Resolvable Latest
direct dependencies:
integration_test ✗0.8.1 ✗0.8.1 ✗0.8.1 ✗1.0.2+3
dev_dependencies: all support null safety.
You are already using the newest resolvable versions listed in the 'Resolvable' column.
Newer versions, listed in 'Latest', may not be mutually compatible.
This means that it's legacy and doesn't have support.
To solve this I changed the pubspec.yaml from this:
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
provider: ^6.0.1
test: ^1.19.5
integration_test: ^0.8.1
dev_dependencies:
flutter_test:
sdk: flutter
Changed to this instead:
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
provider: ^6.0.1
test: ^1.19.5
dev_dependencies:
integration_test:
sdk: flutter
flutter_test:
sdk: flutter
After this, I ran flutter pub get on the terminal and the error disappeared.
Now when I hover over the watchPerformance() method I get this info:
Future<void> watchPerformance(Future<void> Function() action, {String reportKey = 'performance'})
package:integration_test/integration_test.dart
Watches the [FrameTiming] during action and report it to the binding with key reportKey.
This can be used to implement performance tests previously using [traceAction] and [TimelineSummary] from [flutter_driver]
This is a general programming error that will occur. I will put an answer in because the error description for these is often rubbish at telling you what is going on here.
The error is telling you the function called watchPerformance on the object IntegrationTestWidgetsFlutterBinding (a var here called binding), does not exist.
Does the function use a captial W instead of lower case? Take another look at the docs and check everything is spelled correctly etc.

Incomplete import in the generated_plugin_registrant.dart

I have a plugin created using the federated approach. The problem is that the generated_plugin_registrant.dart contains an incomplete import which is pointing to the app-facing package but leaves out the dart file name and this causes an error.
import 'package:my_plugin/'; // PROBLEMATIC LINE
import 'package:my_plugin_web/my_plugin_web.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
// ignore: public_member_api_docs
void registerPlugins(Registrar registrar) {
.registerWith(registrar); // PROBLEMATIC LINE
MyPluginWeb.registerWith(registrar);
registrar.registerMessageHandler();
}
This code is in the default example app for a plugin with an unchanged default pubspec.yaml.
Here's the pubspec.yaml for the app-facing "my_plugin" package:
name: my_plugin
description: A new flutter plugin project.
version: 0.0.1
author:
homepage:
environment:
sdk: '>=2.12.0 <3.0.0'
flutter: '>=1.20.0'
dependencies:
flutter:
sdk: flutter
my_plugin_platform_interface:
path: ../my_plugin_platform_interface
my_plugin_web:
path: ../my_plugin_web
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
plugin:
platforms:
android:
package: com.example.my_plugin
pluginClass: MyPlugin
ios:
pluginClass: MyPlugin
web:
defaultPackage:
path: my_plugin_web
I've tried all the usual commands like flutter clean and recreating the project but to no avail.
Under your web definition (which Google wants in a separate project you have to specify it as
web:
pluginClass: The class name of your web class here
fileName: The file name of the file that holds your web class here
I had it has just "file" and yours is "path" which will cause this.
The issue is that plugin support for the web was not generated for a specific package or packages.
Try creating an analysis_options.dart and add these lines
analyzer:
exclude: [lib/generated_plugin_registrant.dart]
then configure your vscode/.settings.json with these lines
"dart.analysisExcludedFolders":["./yourApp/lib/generated_plugin_registrant.dart" ]
Just find the answer, basically you need to use default_package to specify your are using the integrated plugin. More here

Flutter | Dart : Target of URI does not exist

I am making my first Application to build an Android App with Flutter.
I am using Android Studio as IDE.
The problem is when I import the http package:
import 'package:http/http.dart' as http;
I get an error :
error: Target of URI doesn't exist: 'package:http/http.dart'.
(uri_does_not_exist at [flutter_crypto] lib\home_page.dart:3)
That's my code :
Future<List> getCurrencies() async{
String cryptoUrl = "https://api.coinmarketcap.com/v1/ticker/?limit=50";
http.Response response = await http.get(cryptoUrl);
return JSON.decode(response.body);
}
Thanks,
You need to add the HTTP dependency to pubspec.yaml as per below.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
http: ^0.12.0
With the dependency added you then need to run the following command to update/install required packages:
flutter packages upgrade
Hope this helps
Make sure you have added the dependency to pubspec.yaml
dependencies:
http: ^0.12.0
You will also need to:
flutter packages get
For any upcoming problem with importing packages from dart please go to official Dart website packages and search for needed package and you will find solution up there.
for your issue go to:
https://pub.dartlang.org/packages/http
Installing tap https://pub.dartlang.org/packages/http#-installing-tab-
follow guide steps:
In pubspec.yaml file:# dependencies
dependencies:
http: ^0.12.0
flutter:
(NB: please make sure that http & flutter or any other attribute inside dependencies are aligned as above and they are at same line)
In terminal run below command:
$flutter packages get
run: dart pub --trace get --no-precompile in android srudio Terminal