How to avoid writing an import for every single file in dart/flutter?

Yes there is, you can use export to achieve what you want.

You can place all your widgets in a folder, for example libs/src/ and then create file custom_widgets.dart in libs/ and use export like this inside custom_widgets.dart:

export 'src/custom_multiplechoice.dart';
export 'src/custom_singlechoice.dart';
export 'src/custom_time.dart';
export 'src/custom_widgets/src/custom_yesnochoice.dart';
export 'src/custom_date.dart';

Once you import custom_widgets.dart, all those widgets will be available to you.

Check this out, its all explained here: Dart: Organizing a library package

Update:

In Dart there are no namespaces like in most other languages. Dart uses libraries for encapsulation, data hiding. Only way to import a class into your code is to use import in the beginning of your file, which should also be a library.

I have an issue with this too. Imagine a situation where you want to import library dynamically. Let's say you would like to implement MVC pattern in your application, if you are doing this on the server, you would have a Router class that would analyze URL and decide what Controller class to instantiate and what Method from that Controller to invoke. Now every URL would trigger different Controller, and you don't know it in advance, its up to your Router to detect a Class to instantiate. What you need to do in this situation is import every Controller that could get instantiated at the beginning of your file. And I have issues with that. What if your application gets big and you have to import lets say 20 Controller classes, just so Router / Dispatcher can invoke one of them, and in reality you will invoke only one Controller, as there is only Controller per URL.

Don't have issues with manual loading of Libraries, if they are going to be used, but for situation like described above, Dart fails as there is no "auto loading" of classes like in for example PHP, where you can use auto loaders that use namespaces to find out about location of your class and instantiate a class in the middle of the code dynamically.


There is this extension for VSCode which can help to create this.

Dart Barrel File Generator

Tags:

Dart

Flutter