flutterdartproject-organization

What's the best way to organize and import assets and packages?


So here is my dilemma.

I am a first time user of Flutter and Dart. I come from a background of C++ and C#, which use include statements for modularizing and separating classes, assets, and so on.

There appear to be some similarities between how those "include" statements from C-brand languages work, and how "import" statements work in Flutter and Dart.

I do not need to know how to directly use the import statements - that part is clear enough. What I'm asking is, if I were to desire usage of several packages from pub dot dev in my project, after adding them to my pubspec.yaml and running flutter get, what would be the best and/or most efficient way of using those packages across the entirety of the project?

My own thought so far (again, being new to the tool and the language) would be to simply create a separate .dart file, import all of my packages, and then use that dart file for creation of custom widgets across all packages I care to use. Then, for the main dart files within the project, all I have to include is my "global" file, and reference the custom widgets where needed. I have not tried this yet as it is for my job, and I want to do it the "right" way the first time rather than having to go back all hopped up on energy drinks and Excedrin to try and refactor later.

Is there a Flutter/Dart expert in the house who can provide some guidance or suggestions on this issue? I'm sorry it's not some oddly specific question with a straightforward answer, so hopefully someone or several people can provide useful insight on how to organize code assets within the project. Thanks in advance!


Solution

  • Note: this question might be "opinion based"

    The way I like to do imports is called "barrel" imports:

    it will cut down from multiple imports to a single import.

    Create a file my_import.dart:

    export 'airplane.dart';
    export 'bus.dart';
    export 'ship.dart';
    export 'train.dart';
    

    and now, instead of importing every single file above (airplane.dart, bus.dart, etc.)

    you can just import my_import.dart instead.


    And actually, if you take a look at the official material.dart file, you'll see that that's what they do:

    export 'src/material/about.dart';
    export 'src/material/action_buttons.dart';
    export 'src/material/action_chip.dart';
    ...
    

    See also