Error:
When compiling my file I get the following error: library is in a package that is not known
This is referring to the file: home.dart under my pages folder.
These are my dependencies on the pubspec.yaml file:
dependecies:
flutter:
sdk: flutter
http: "^0.12.0+1"
intl: "^0.15.8"
charts_flutter: "0.6.0"
cupertino_icons: ^0.1.2
My code:
import 'package:fLutter/materiaL.dart';
import 'package:charts_fLutter/fLutter.dart' as charts
class PieChart extends StatefulWidget {
final Widget child;
override
PieChart({Key key, this.child}) : super(key: key);
_PieChartState createState() => _PieChartState();
class GPieChartState extends State<PieChart> {
List<charts.Series<Effl,String>> _seriesPieData;
_generateData() {
var pieData = [
new Effl( ' > ObJectlf ' , 35.8, Colors.bZue[6oo]),
new Effl( ' < ObJectlf ' , 8.3, Colors.red[6oo]),
Ok, so looking at the error it says
Refers, in an import, to the following library:
package:efficience001/pages/home.dart
That library is in a package that is not know. Maybe you forgot to mention it in your pubspec.yaml file?
This means Flutter didn't manage to find the file home.dart under the pages directory.
Since you say that it worked before, the only possible logical explanation is that you have renamed, deleted, or moved the file "home.dart" or its parent folder.
Related
I want to build a Cordova plugin for Ionic app, and this plugin I think I have already imported the library (here is the java code, as you can see I write the import statement)
package session;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.Manifest;
import android.os.Handler;
import android.javax.sip.Dialog;
import java.lang.ref.WeakReference;
public class MediaSipSession extends CordovaPlugin{
private static String TAG = "MediaSipSession";
public static CallbackContext callCallback;
private CallbackContext RTCPCallbackContext;
private Dialog dialog;
And I also add the source-file tag in my plugin.xml ( android-jain-sip-ri-1.2.342.jar have the class which name android.javax.sip)
<source-file src="libs/android-4.1.1.4.jar" target-dir="libs/android-4.1.1.4.jar"></source-file>
<source-file src="libs/android-jain-sip-ri-1.2.342.jar" target-dir="libs/android-jain-sip-ri-1.2.342.jar"></source-file>
so I run ionic Cordova build android, expect Ionic will build an android APK for android platform, but I get the error, it say
error: package android.javax.sip does not exist
import android.javax.sip.Dialog;
symbol: class Dialog
location: class MediaSipSession
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
hope anyone can fix this problem.
I found the way to solve this problem.
If you want to use the library, should use the lib-file tag to define the .jar file, not the source-file tag : )
I want to use SVG/Vector Graphics in my Flutter Application.
is there any library or Dart Package which can be used?
steps
use this plugin flutter_svg
https://pub.dartlang.org/packages/flutter_svg
adding images to Assets
import and adding this widget
SvgPicture.asset('assets/images/Defect/icon${values[index].childId}.svg', height: 50.0,),
To display the SVG from Assets in Flutter.
Add the following code in pubspec.yaml file under dependencies
flutter_svg: ^0.22.0
Add the following code in the header of your main.dart
import 'package:flutter_svg/flutter_svg.dart';
Assign the SVG to one variable like final String assetName = 'assets/images/avatar.svg';
new SvgPicture.Asset(assetName, height:100, width:100,)
I have a text file (.txt) that I'd like to be an asset that I can scan in later.
In the pubspec.yaml, I've made sure that:
flutter:
assets:
- res/my_file.txt
exists. The file resides in the res/ folder that I made, on the same level as lib/android/ and ios/
I'm trying to read the file from a custom class, not a widget.
According to the documentation, I'm to use this import:
import 'package:flutter/services.dart' show rootBundle;
and start reading like so:
/// Assumes the given path is a text-file-asset.
Future<String> getFileData(String path) async {
return await rootBundle.loadString(path);
}
And to get the actual data, do:
String data = await getFileData(fileName);
However, when I use a fileName like 'assets/res/my_file.txt', I get an error: Unable to load asset: assets/res/my_file.txt.
It's also worth noting that I'm trying to do this from a unit test. Any ideas on how to properly do this? Thanks!
Here is a fuller answer for future visitors.
Create an assets folder
Create an assets folder in your project's root folder. In Android Studio you can right click the Project outline and go to New > Directory.
You can create another subfolder for text files in assets if you like. But if you do, you have to include the relative path in pubspec.yaml. See below.
Add your text file to the new folder
You can just copy your text file into the assets directory. The relative path of my_file.txt, for example, would be assets/my_file.txt.
Register the assets folder in pubspec.yaml
Open the pubspec.yaml file that is in the root of your project.
Add an assets subsection to the flutter section like this:
flutter:
assets:
- assets/my_file.txt
If you have multiple files that you want to include, then you can leave off the file name and just use the directory name (include the final /):
flutter:
assets:
- assets/
Get the text in code
You can use the global rootBundle to get the text file asset:
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
Future<String> loadAsset() async {
return await rootBundle.loadString('assets/my_text.txt');
}
Or if you have the BuildContext (inside a widget) you can use DefaultAssetBundle. This is recommended because it allows switching asset bundles at runtime, which is useful for multilingual assets.
Future<String> loadAsset(BuildContext context) async {
return await DefaultAssetBundle.of(context).loadString('assets/my_text.txt');
}
See also
Loading text assets
How to include images in your app
The folder name "assets" isn't magically added. Update your pubspec.yaml to include the full path to the asset.
flutter:
assets:
- assets/res/my_file.txt
In my opinion, in order to load a js file into a flutter, you should consider it as a text file and load it properly. So, you need to add the file to assets folder, add into a pubspec file, then load it. read the full answer here
Second, you used evalJavascript. this function can be used in many different situations. but it will work only if you have a view panel.
Check below example:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
main() async {
String jsCode = await rootBundle.loadString('assets/javascript.js');
runApp(new MaterialApp(
home: LunchWebView(jsCode),
));
}
class LunchWebView extends StatelessWidget {
final String text;
LunchWebView(this.text);
#override
Widget build(BuildContext context) {
final FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
flutterWebviewPlugin.launch('https://www.google.com');
flutterWebviewPlugin.evalJavascript(text);
return Container();
}
}
Is there any way to access some of the attributes listed in a pubspec.yaml file in that files Dart application?
In particular, the version and description attributes may be quite useful to see in a version info dialog, or even a '--version' when using a console app. I haven't been able to find a way to access in the API. I'm not sure if Mirrors would have anything appropriate, but if a web app is compiled to JS, then I don't see the description anywhere in the output JS.
Thanks.
EDIT
feature request: https://code.google.com/p/dart/issues/detail?id=18769
FOR FLUTTER ONLY
Please use this new package package_info_plus from flutter community.
import 'package:package_info_plus/package_info_plus.dart';
PackageInfo packageInfo = await PackageInfo.fromPlatform();
String appName = packageInfo.appName;
String packageName = packageInfo.packageName;
String version = packageInfo.version;
String buildNumber = packageInfo.buildNumber;
BELOW SOLUTION IS DEPRICATED.
I know the OP wants to read YAML but for flutter dev's you guys can read the version and other info of the application using package_info.
This is the sample to fetch details from Android/iOS application.
import 'package:package_info/package_info.dart';
PackageInfo packageInfo = await PackageInfo.fromPlatform();
String appName = packageInfo.appName;
String packageName = packageInfo.packageName;
String version = packageInfo.version;
String buildNumber = packageInfo.buildNumber;
you can install the "dart_config" package and use this code to parse a pubspec.yaml file:
import 'package:dart_config/default_server.dart';
import 'dart:async';
void main() {
Future<Map> conf = loadConfig("../pubspec.yaml");
conf.then((Map config) {
print(config['name']);
print(config['description']);
print(config['version']);
print(config['author']);
print(config['homepage']);
print(config['dependencies']);
});
}
The output looks similar to this:
test_cli
A sample command-line application
0.0.1
Robert Hartung
URL
{dart_config: any}
EDIT
You can do it with the Yaml package itself:
*NOTE: this will not work on Flutter Web
import 'package:yaml/yaml.dart';
import 'dart:io'; // *** NOTE *** This will not work on Flutter Web
void main() {
File f = new File("../pubspec.yaml");
f.readAsString().then((String text) {
Map yaml = loadYaml(text);
print(yaml['name']);
print(yaml['description']);
print(yaml['version']);
print(yaml['author']);
print(yaml['homepage']);
print(yaml['dependencies']);
});
}
Regards Robert
None of the above answers worked for me, but here's a working solution for a Flutter app:
In your pubspec.yaml add the "pubspec.yaml" to assets:
assets:
- assets/
- pubspec.yaml
If you have a widget where you need to show the app version like this:
...
Container(
child: Text('Version: 1.0.0+1'),
),
...
Wrap your widget with a FutureBuilder like this:
import 'package:flutter/services.dart';
import 'package:yaml/yaml.dart';
...
FutureBuilder(
future: rootBundle.loadString("pubspec.yaml"),
builder: (context, snapshot) {
String version = "Unknown";
if (snapshot.hasData) {
var yaml = loadYaml(snapshot.data);
version = yaml["version"];
}
return Container(
child: Text(
'Version: $version'
),
);
}),
...
The services rootBundle property contains the resources that were packaged with the application when it was built.
If you want to show the version without the build number, you can split the string like so:
'Version: ${version.split("+")[0]}'
UPDATE: As mentioned by #wildsurfer, this approach has a potential security risk in web development because the pubspec.yaml is shared with the browser!
So assuming that this is for a dart cli application then the #Robert suggestion won't work.
dart_config isn't available for dart 2.x and your pubspec.yaml isn't going to be relative to your cwd except when you are in your development environment
So you need to get the pubspec.yaml relative to the libraries executable path.
This example uses the 'paths' package but it isn't required.
This can be obtained by:
import 'package:path/path.dart';
String pathToYaml = join(dirname(Platform.script.toFilePath()), '../pubspec.yaml');
You can now read the yaml:
import 'package:path/path.dart';
import 'package:yaml/yaml.dart';
String pathToYaml = join(dirname(Platform.script.toFilePath()), '../pubspec.yaml');
File f = new File(pathToYaml);
String yamlText = f.readAsStringSync();
Map yaml = loadYaml(yamlText);
print(yaml['name']);
print(yaml['description']);
print(yaml['version']);
print(yaml['author']);
print(yaml['homepage']);
print(yaml['dependencies']);
});
For Flutter only (Web, Android and IOS)... since October 2020
If you want your app working on Web, Android and IOS use "Package info_plus" instead.
How to Incorporate Automated Version Information into A Dart Command Line App
To update version information in your code without having to package a resource file to be parsed during run time, you can have the information hard coded into an automatically generated dart source file which gets compiled into your binary. The following example hard codes the version, name, and description information into the Map object "meta" in a meta.dart file. The meta.dart file is recreated and overwritten every time the test suite is run in development. To verify the source code has the correct version information, the app's code verifies the version and other meta information against the attributes in the pubspec.yaml file (but only when run as interpreted code in development). If there is a difference from pubspec.yaml, it throws an exception. Once compiled into a binary, it will skip that check as it won't find the pubspec.yaml file, so no error is thrown from the binary. Even if a pubspec.yaml file happens to be around and is found, it only throws an exception and does not create a "meta.dart" source file.
1. Create a MetaUpdate class and save it as "meta_update.dart":
import 'dart:io';
import 'package:yaml/yaml.dart';
import 'meta.dart';
class MetaUpdate {
String pathToYaml = "";
String metaDartFileContents = "";
MetaUpdate(this.pathToYaml);
void writeMetaDartFile(String metaDartFilePath) {
File metaDartFile = File(metaDartFilePath);
String metaDartFileContents = """
/// DO NOT EDIT THIS FILE EXCEPT TO ENTER INITIAL VERSION AND OTHER META INFO
/// THIS FILE IS AUTOMATICALLY OVER WRITTEN BY MetaUpdate
Map<String, String> meta = <String, String>{
"name": "${getPubSpec('name')}",
"description":
// ignore: lines_longer_than_80_chars
"${getPubSpec('description')}",
"version":"${getPubSpec('version')}",
};
""";
metaDartFile.writeAsStringSync(metaDartFileContents);
}
String getPubSpec(String pubSpecParam) {
File f = File(pathToYaml);
String yamlText = f.readAsStringSync();
// ignore: always_specify_types
Map yaml = loadYaml(yamlText);
return yaml[pubSpecParam];
}
void verifyLatestVersionFromPubSpec() {
try {
File f = File(pathToYaml);
//exit if no pubspec found so no warning in production
if (!f.existsSync()) return;
//compare meta.dart with pubspec meta and give warning if difference
if (meta.keys
.where((dynamic e) => (meta[e] != getPubSpec(e)))
.isNotEmpty) {
throw Exception(
"""Version number and other meta attributes in code are different from pubspec.yaml. Please check pubspec.yaml and then run test so that MetaUpdate can update meta information in code, then recompile""");
}
} on Exception {
rethrow;
}
}
}
2. Create a "meta.dart" file:
/// DO NOT EDIT THIS FILE EXCEPT TO ENTER INITIAL VERSION AND OTHER META INFO
/// THIS FILE IS AUTOMATICALLY OVER WRITTEN BY MetaUpdate
Map<String, String> meta = <String, String>{
"name": "Acme Transmogrifier",
"description":
"The best dart application ever.",
"version":"2021.09.001",
};
When you initially create the meta.dart file, copy your specific info from pubspec.yaml. This will later be overwritten each time your MetaUpdate.writeMetaDartFile() is run, changing the contents whenever the info in pubspec.yaml is changed.
3. Implement The Version Update In Your Test Code
Add the following in the first line of Main() in your test code (not the source of the main program, we don't want it to be compiled into the binary), changing the path to meta.dart as appropriate:
MetaUpdate("pubspec.yaml").writeMetaDartFile("lib/src/meta.dart");
4. Add A Meta Check To Your Main Code
Put this in your app's code so it is one of the first methods executed when your app is run - it will generate an exception if there is a difference between the attributes shown in the meta.dart and pubspec.yaml:
MetaUpdate("pubspec.yaml").verifyLatestVersionFromPubSpec();
5. Using
Make sure the Name, Version, and Description information in pubspec.yaml contains the latest information you want reflected in your code.
Import "meta.dart" and insert meta['name'], meta['version'], etc. where you need them to be shown (e.g., in --help or --version messages to be printed to the console).
As long as you run your tests before compiling your code the meta information will be accurately reflected in your code.
You can access pubspec.yaml properties with the official pubspec_parse package from the Dart team.
dart pub add pubspec_parse
import 'dart:io';
import 'package:pubspec_parse/pubspec_parse.dart';
final pubspec = File('pubspec.yaml').readAsStringSync();
final parsed = Pubspec.parse(pubspec);
You can then access typed properties on the parsed object.
You can find supported properties here: https://pub.dev/documentation/pubspec_parse/latest/pubspec_parse/Pubspec-class.html.
I am on angulardart 0.11.0 and this is my code for main.dart:
library my_app_main;
import 'package:angular/angular.dart';
import 'package:angular/application_factory.dart';
import 'package:my_app/src/something.dart';
class MyModule extends Module {
MyModule() {
bind(MyAppCtrl);
bind(MyComp);
}
}
main() {
applicationFactory()
.addModule(new MyModule())
.run();
}
I get syntactic errors:
angular.dart import is 'unused'
'Module' is an 'undefined class'
I have tried deleting and rebuilding the packages directory, pubspec file, etc. What is going on?
angular.dart import is 'unused' is just a warning, so you don't really need to worry about it.
You're seeing 'Module' is an 'undefined class' because you're not importing the di library. Add
import 'package:di/di.dart'; to your imports and it should run.
Turns out the error was caused by the angular files becoming corrupted in the pub cache. As was pointed out here (https://groups.google.com/forum/#!topic/angular-dart/WiZuIwxTDb4) - thanks Günter! - the solution is to repair the pub cache by doing 'pub cache repair' or at least 'pub cache add angular'