I found myself written tedious code when importing files into dart files like the following:
import '../../constants.dart';
I'm wondering if there is any way to create an alias to specific folder like:
import '#shared/constants.dart';
Thanks,
Javi.
Dart doesn't allow you to rename imported identifiers, but it allows you to specify an import prefix
import '../../constants.dart' as foo;
...
foo.ImportedClass foo = foo.ImportedClass();
It allows also to filter imported identifiers like
import '../../constants.dart' show foo hide bar;
See also
https://www.dartlang.org/guides/language/language-tour#libraries-and-visibility
What is the difference between "show" and "as" in an import statement?
Barrel files can also make importing easier like
lib/widgets/widgets.dart
export 'widget1.dart';
export 'widget2.dart';
export 'widget3.dart';
export 'widget4.dart';
lib/pages/page1.dart
import '../widgets/widgets.dart';
Widget build(BuildContext context) => Widget1();
No. Dart do not have import alias.
But you have absolute imports which makes up for it:
import 'package:my_lib/shared/constants.dart
This will import the file /lib/shared/constants.dart
Related
I import a package and would forward a member of it. What syntax does Dart offer for that?
foo.dart
import 'package:xzy/xzy.dart'; // contains class Xyz
// how do I forward Xyz here to make it available in bar.dart?
bar.dart
import 'package:mypackage/foo.dart';
Xyz is hidden here
You can use export
import 'package:xzy/xzy.dart';
export 'package:xzy/xzy.dart' show Xyz;
or just
export 'package:xzy/xzy.dart' show Xyz;
You don't need to import for that. Just export is enough if you don't need Xyz in this re-exporting file.
See also
https://www.dartlang.org/guides/libraries/create-library-packages
What is the difference between "show" and "as" in an import statement?
I develop a flutter app, define serveral models in 'model' package.
Then I declare a class Example in 'model' for example.
model/example.dart
class Example {
#override
String toString() {
return 'class example';
}
}
test_a.dart
import 'package:example/model/example.dart'
Example testA() {
return Example()
}
test.dart
import 'model/example.dart'
import 'test_a.dart'
test() {
Example example = testA();
if (example is Example) {
print('this class is Example');
} else {
print('$example');
}
}
I will get output class example🌚
If I change from import 'model/example.dart' to import 'package:example/model/example.dart' in test.dart, then I will get the output this class is Example.
So I'm confused what is different between the full path and relative path in dart.
package imports
'package:... imports work from everywhere to import files from lib/*.
relative imports
Relative imports are always relative to the importing file.
If lib/model/test.dart imports 'example.dart', it imports lib/model/example.dart.
If you want to import test/model_tests/fixture.dart from any file within test/*, you can only use relative imports because package imports always assume lib/.
This also applies for all other non-lib/ top-level directories like drive_test/, example/, tool/, ...
lib/main.dart
There is currently a known issue with entry-point files in lib/* like lib/main.dart in Flutter. https://github.com/dart-lang/sdk/issues/33076
Dart always assumed entry-point files to be in other top-level directories then lib/ (like bin/, web/, tool/, example/, ...).
Flutter broke this assumption.
Therefore you currently must not use relative imports in entry-point files inside lib/
See also
How to reference another file in Dart?
I tried to use the router in angular2-beta.20 in Dart with the HashLocationStrategy.
But I couldn't find any docs, except for
this link to angular2-beta.15 docs, which are incomplete.
The example shows TypeScript imports instead of Dart ones.
So I tried to import package:angular2/router.dart, but the Dart Analyzer keeps complaining that it can not find LocationStrategy and HashLocationStrategy
Also I don't know, how to write the import exactly, because a top-level provide function, as in the example above, seems non existent.
provide(LocationStrategy, {useClass: HashLocationStrategy})
After some research I found the following:
LocationStrategy and HashLocationStrategy are now part of
package:angular2/platform/common.dart instead of package:angular2/router.dart.
The bootstrap()- method is platform specific, so we need to import package:angular2/platform/browser.dart.
We need to import package:angular2/router.dart to have ROUTER_PROVIDERS available in bootstrap() method.
Here is a working code example for the dart file initializing :
// needed to import "bootstrap" method
import 'package:angular2/platform/browser.dart';
// needed to import LocationStrategy and HashLocationStrategy
import 'package:angular2/platform/common.dart';
// needed for Provider class
import 'package:angular2/angular2.dart';
// needed to import ROUTER_PROVIDERS
import 'package:angular2/router.dart';
// import your app_component as root component for angular2
import 'app_component.dart';
void main() {
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
const Provider(LocationStrategy, useClass: HashLocationStrategy)
]);
}
Hope this helps somebody! :)
Say, I load this script in the browser:
<script src='app.dart' type='application/dart'></script>
Now, in app.dart I have this:
import 'library1.dart';
unleashTheKraken();
Then in library1.dart you'll find this:
library library1;
import 'library2';
And finally in library2.dart we'll have:
library library2;
unleashTheKraken() => print('Unleashing the Kraken')
And the result is: Exception: No top-level method 'unleashTheKraken' declared. How so?
Because imports don't chain automatically. You have to use the export statement for that.
library library1;
import "library2.dart";
export "library2.dart";
And to avoid unnecessary code: import and export are completely independent. If you don't use unleashTheKraken in library1 itself, you can omit the import statement and just use export alone.
I know you can use the library, import and even #import, but which is correct?
I have got two files, MainClass.dart and Library.Dart, and I want to add a reference to Library.dart in MainClass.dart. How can I do that?
Firstly let me just preface this by saying please do not use the hash symbol before import or library or anything else. This is an old syntax that is being deprecated. So we no longer want to use #import('...') The correct syntax is:
import 'some_file.dart';
That said, there are two different things we can do to access different dart source files within our current file. The first is to import the file. We use this such as in your case when you want to bring a different library into the current file (or more accurately current library).
Usually if your files are in the same directory, or a sub directory of the current one we would import them like this:
import 'lib/library.dart';
However If you are using the pub package layout you can also use some special short-cut references as well to import files (particularly from other packages you've imported). I highly suggest reading the documents on the pub site, as most applications and libraries are designed with this in mind. It also has suggestions on best naming conventions such as filenames in all lower case, and using underscore for spaces, and directory layouts.
The other important thing to know about bringing a dart file into another file, is that we can use the part and part of directives. This used to be called #source but was changed (with the removal of the hash sign) to reduce confusion. The part directive is used when we want to write a single library which spans multiple files. Say for instance you have an Awesome Library, which is starting to get a little large for a single file. We will create the main file of the library (not to be confused with the main method). This file will usually have the same name as the library itself.
// awesome_library.dart
library awesome_library;
import 'dart:math';
import '...';
// this injects all the content of secret_file.dart
// into this file right here almost as if it was
// here in the first place.
part 'src/secret_file.dart';
// The rest of our file here
// ...
The part directive basically takes everything from our src/secret_file.dart and inserts it into that part of the file. This allows us to split our huge Awesome Library into multiple smaller files that are easier to maintain. While not specifically required, it is helpful to use the part of directive in our secret_file.dart to help the editor know that it is "part of" the library.
// secret_file.dart
part of awesome_library;
// ... Rest of our secret_file code below.
Note that when using a part file like this, the part(s) (that is everything that is not the main file of the library) cannot import or use library declarations themselves. They import whatever is imported into the the main file, but they cannot add any additional imports.
For more information about library see this link.
Importing your own created libraries:
You will be importing the filename.dart and not the name of your library.
So if the name of your library is: myLib and it is saved in the file: someDartFile.dart you will have to
import 'someDartFile.dart';
If you have on Windows a library at: K:\SomeDir\someFile.dart you will need to write:
import '/K:/SomeDir/someFile.dart';
example:
import 'LibraryFile.dart'; //importing myLib
void main(){
//a class from myLib in the LibraryFile.dart file
var some = new SomeClassFromMyLibrary();
}
myLib in LibraryFile.dart:
library myLibrary;
import 'dart:math';
class SomeClassFromMyLibrary{
String _str = "this is some private String only to myLibrary";
String pubStr = "created instances of this class can access";
}
Here a full example.
//TestLib.dart
import 'LibFile.dart'; //SomeLibrary
void main() {
print("Hello, World!");
LibFile l = new LibFile();
print(l.publicString);//public
print(l.getPrivateString);//private
print(l.getMagicNumber); //42
}
//LibFile.dart
library SomeLibrary;
part 'LibFile2.dart';
class LibFile {
String _privateString = "private";
String publicString = "public";
String get getPrivateString => _privateString;
int get getMagicNumber => new LibFile2().number;
}
//LibFile2.dart
part of SomeLibrary;
class LibFile2 {
int number = 42;
}
Although i am answering very late, but the answer may help new developer.
Always use pubspec.yaml file in your dart package(application/library).
once you run pub get command it will add your local library in the dependencies list in .packages file.
Consider i have following project structure.
To refer to the content of greeting.dart in my main.dart file i should add the library as below
import 'package:my_project_name/greeting.dart'
Once imported we can use the content of greeting.dart file in our main.dart file.
Note: we have not used the actual path as you can see 'lib' directory is missing.
First make sure that's the name which you have mentioned in pubspec.yaml and the file you want to import are sharing the exact same name
example:
pubspec.yaml
name: flutter_wordpress_app
description: flutter wordpress app
...
....
// dirOne/dirTwo/greeting.dart
class FavArticleBloc {
// Your code goes here
}
import 'package:flutter_wordpress_app/dirOne/dirTwo/greeting.dart'
void main(){
var some = new FavArticleBloc();
}
But
in the main.dartyou don't need to specify
import 'package:flutter_wordpress_app
just do like below
import 'dirOne/dirTwo/greeting.dart