Handling Flutter Imports like a Pro

Maruf Hassan
3 min readMay 2, 2021

This is Part #1 of the series in Flutter Production Level Development where I teach you all the tips and tricks used in an Industry Level Production app.

If you prefer videos over articles then you can watch the companion 25 secs #Short video on this article.

When building a production-ready app, it is a good practice to break the widgets into different dart files. This increases readability and helps in debugging but while doing so, we end up with tons of imports something like this.

import 'package:flutter/material.dart';
import 'package:map_ui/screens/airplane.dart';
import 'package:map_ui/screens/bus.dart';
import 'package:map_ui/screens/train.dart';
import 'package:map_ui/screens/ship.dart';

If only there was a way to reduce these imports at the beginning of each file.

Guess what, there is!

We create Barrel files.

A barrel is a way to rollup of imports from several files into a single convenient file.

So we have a simple project here that shows different modes of transportation.

We have four icons in four different dart files and each file needs to be imported in the main.dart file to display it.

To cut down from multiple imports to a single import, we create a barrel file.

We make a barrel by creating a dart file and putting all the imports in it.

1. Create a dart file with the same name as the folder name, here we have the folder name as screens so our barrel file will be screens.dart

2. Add all the files in the folder with export as the prefix.

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

3. Replace the four individual imports by importing the screen.dart file

import 'package:map_ui/screens/screens.dart';

Now the imports in our main.dart looks like this.

We have successfully created our barrel file and our code looks a lot cleaner than before.

Now if we add a new file to the screen folder, we will have to add it in the screens.dart again each time.

I know what you are wondering. Isn’t there a better way to do it rather than typing the exports every time?

Well, there is!

There is this VSCode Extension called Dart Barrel File Generator by Miquel de Domingo i Giralt which helps you to create and update your Barrel files with the click of a button.

Just install the extension and right-click on the folder in which you want a barrel file.

Click on the GDBF: Current Folder Only and it will create a barrel file as well as update a barrel file with the new files if you have added new files to the folder.

Dart Barrel File Generator
Dart Barrel File Generator

I hope you liked the article. I plan to bring more short articles like these to teach tips and tricks used in Production Level Flutter Development!

You can read about Handling Flutter Strings like a Pro in Part #2 of the series.

You can follow me on Twitter, Github or Youtube to stay updated with all my new articles and videos.

--

--