package is forbidden but only when it's imported - flutter

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
...
...

Related

freezed package can not generate toJson code for nested object anymore

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.

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

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

How to upgrade packages in VSCode/flutter?

I'm using VS Code on a flutter project. I just edited pubspec.yaml to point to a later version of a package, and it automatically ran 'flutter packages get'. In my '/development//flutter/.pub-cache/hosted/pub.dartlang.org' directory, I can see both versions. But when I compile, it looks like it's still using the old version. I tried various things like 'flutter packages upgrade', 'flutter clean', etc., but to no avail. Looking at the 2 package versions' source code, I can see the change I want in the newer version. How do I point to the new package? Thanks.
Update:
It's the 'ethereum' package that's not updating. I had used the 3.0.0 version (method expects 2 args), and then switched to the 3.1.0 version (method expects 3 args). But compiling with a 3 arg call balks with incorrect argument count:
client.admin.personalSendTransaction(BigInt.parse(currentAddress), currentPassword,{});
[dart] Too many positional arguments: 2 expected, but 3 found. [extra_positional_arguments_could_be_named]
Yet hovering over the method call does show it expects 3 args:
personalSendTransaction(BigInt address, String passphrase, {BigInt to, BigInt data, int gas, int gasPrice, int value, int nonce, int condition, bool conditionIsTimestamp: false}) → Future<BigInt>
pubspec.yaml:
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
# Get package(s) for talking to ethereum node
# web3dart: '>=0.3.0'
ethereum: ^3.1.0
# read barcodes and QR codes
barcode_scan: ^0.0.3
# Generate a QR code
qr: ^1.0.1
# Display as actual symbol
qr_flutter: ^1.1.5
dev_dependencies:
flutter_test:
sdk: flutter
In pubspec.lock:
ethereum:
dependency: "direct main"
description:
name: ethereum
url: "https://pub.dartlang.org"
source: hosted
version: "3.1.0"
Version 3.1.0 is what I want to be used.
Running 'flutter packages upgrade resolved' yields:
[Gregorys-iMac]:(gkd) ~/Programs/wine_track $ flutter packages upgrade resolved
Running "flutter packages upgrade" in .... 2.7s
In the package cache, I have both:
/Users/gkd/development//flutter/.pub-cache/hosted/pub.dartlang.org/ethereum-3.0.0/lib/src/api/ethereum_api_admin.dart
/Users/gkd/development//flutter/.pub-cache/hosted/pub.dartlang.org/ethereum-3.1.0/lib/src/api/ethereum_api_admin.dart
flutter pub upgrade --major-versions
you can simply run flutter packages upgrade in your project to upgrade all the packages. this feature is available from flutter version 1.17
Just use
flutter pub upgrade --major-versions
or
flutter packages upgrade
i have created a python3 script for this, you can use. this script only produce latest packages names and versions, you must to copy and paste into pubspec.yaml file.
import yaml
import requests
from lxml import etree
from io import StringIO
def getNewVersion(pkg_name):
url = f'https://pub.dev/packages/{pkg_name}'
with requests.get(url) as req:
doc = etree.parse(StringIO(req.text), etree.HTMLParser()).getroot()
title = doc.xpath('//h2[#class="title"]')[0].text.strip()
return '^' + (title.split(' ')[1])
if __name__ == "__main__":
filename = 'pubspec.yaml'
new_map = None
with open(filename, 'r') as _f:
docs = yaml.load(_f, Loader=yaml.FullLoader)
deps = docs['dependencies']
for package_name, old_version in deps.items():
if package_name == 'flutter':
continue
last_version = getNewVersion(package_name)
print(f'{package_name}: {last_version}')
OK, never mind. This was my mistake. I interpreted the declaration's "{ type:variablename, . . .}" as a map/hash. In reality, they're Dart's optional named parameters. Just using any of them without the wrapping braces compiles clean.
Go to https://pub.dartlang.org/packages and find the latest package from there.
In there you can see an install tab. click that.
Now you can add the dependencies into your pubspec.ymal file in your flutter project.
Then you can just press ctrl+s in VS Code or type flutter packages get in your terminal.
Now you can import into any page.