dart import and part of directives in same file
Asked Answered
L

4

17

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?

Lipfert answered 21/6, 2013 at 14:54 Comment(0)
M
37

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.

Marsupium answered 21/6, 2013 at 15:9 Comment(0)
K
4

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.

Kerosene answered 9/4, 2021 at 15:21 Comment(1)
The Dart team has introduced a new lint rule use_string_in_part_of_directives. So declaring part of library_name; is discouraged.Procreate
D
0

If you are facing this in IntelliJ IDEA or Android Studio while moving the files via drag and drop, then switch to 'Project Source' in project pane at left and then move(drag and drop). When I faced this problem while working with flutter, this worked for me.

Detector answered 19/9, 2021 at 14:2 Comment(0)
B
0

place all your files where you define your library like i defined branch_cubit and all my imports are there and in the branch_state i added par of keyword in the branch_state

Bract answered 16/11, 2023 at 9:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.