When to use part/part of versus import/export in Dart?

前端 未结 3 1446
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 04:04

I do not completely understand the difference between part/part of and import/export when using libraries in Dart. For e

相关标签:
3条回答
  • 2020-12-05 04:26

    Let's suppose we have a Dart library called mylib, whose file is lib/mylib.dart.

    library mylib;
    
    // Definitions
    

    That library can be included in the main.dart file as

    import 'package:mypackage/mylib.dart';
    

    When you create a new library and use other libraries you want to make available automatically when using your package, then you use export:

    library mylib;
    
    export 'otherlib.dart';
    
    // Definitions
    

    You can use the show keyword to import/export only some parts of a library (like a class or something).


    You are using the part of directive wrong here. You can't use both library and part of, which is used to specify the contents that belong to a library. For example, you can split your library file in more than one file (the parts):

    Suppose we have in the file mylib.dart:

    library mylib;
    
    part 'src/class1.part';
    // More parts
    

    And then we have in another file src/class1.part the part specified in mylib.dart

    part of mylib;
    
    class Class1 { 
      /* ... */
    }
    
    0 讨论(0)
  • 2020-12-05 04:35

    The Creating Library Packages article on the dartlang.org site recommends avoiding part / part of.

    Note: You may have heard of the part directive, which allows you to split a library into multiple Dart files. We recommend that you avoid using part and create mini libraries instead.

    The 'mini libraries' referred to are small library dart files in src which are imported into and exported from main libraries.

    0 讨论(0)
  • 2020-12-05 04:42

    update 2018/03

    part and part of is used more and more for code generation scenarios recently (instead of deprecated transformers) and unlikely to go away anytime soon.

    Packages like built_value, json_serializable, and many others depend on it.

    Discouraged is only the patter where all files of a package are tied together to a single library by having one library file and all other files being part of that library.

    original

    In Dart, private members are accessible within the same library. With import you import a library and can access only its public members. With part/part of you can split one library into several files and private members are accessible for all code within these files.

    see clarifications to below paragraph in above update

    Using part / part of is discouraged and the Dart team is considering getting rid of it. I assume they will introduce something like "friend" (https://github.com/dart-lang/sdk/issues/22841), where two libraries can access each other's private members as an alternative before they discontinue part / part of (maybe in a future Dart version).

    0 讨论(0)
提交回复
热议问题