Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dart import and part of directives in same file

Tags:

import

dart

I'm writing a dart file:

import 'something.dart'

part of my_lib;

class A{
    //...
}

I have tried this with the import and part of directives reversed and it still won't work, can you not have a class file as part of a library and have imports?

like image 679
Daniel Robinson Avatar asked Jun 21 '13 14:06

Daniel Robinson


2 Answers

All your imports should go in the file that defines the library.

Library:

library my_lib;

import 'something.dart';

part 'a.dart';

class MyLib {
  //...
}

a.dart

part of my_lib;

class A {
  //...
}

Since a.dart is part of my_lib it will have access to any files that my_lib imports.

like image 137
Pixel Elephant Avatar answered Oct 20 '22 23:10

Pixel Elephant


The Pixel Elephanr's answer is correct, but I suggest the alternative syntax for the part-of directive:

my_file.dart (the library main file):

//This now is optional:
//library my_lib; 

import 'something.dart';

part 'a.dart';

class MyLib {
  //...
}

a.dart (part of the same library; so in it you can reference the elements imported in my_file.dart)

//Instead of this (whitout quotes, and referencing the library name):
//part of my_lib;

//use this (whit quotes, and referencing the library file path): 
part of 'my_file.dart'

class A {
  //...
}

In the Doc you can found both the syntax, but only using the part-of's syntax with quotes (pointing to the file path), you can omit the library directive in the library main file; or, if the library directive is still needed for other reasons (to put doc and annotations to library level), at least you won't be forced to keep in sync the library name in multiple files, which is boring in case of refactoring.

like image 37
Mabsten Avatar answered Oct 21 '22 00:10

Mabsten