Flutter: Using same-name classes imported from different files

Updated: February 15, 2023 By: Augustus Post a comment

To use same-name classes, widgets, or functions imported from different files in a Flutter project without changing their names, you can use the as keyword with a prefix (the name of the prefix is up to you).

Example

Let’s say we have 3 separate files: ./widgets/product_item.dart, ./providers/product_item.dart, and ./models/products_item.dart. Each file of those contains a class named ProductItem. What we have to do now is to import and use them all in main.dart.

.
├── main.dart
├── models/product_item.dart
├── providers/product_item.dart
└── widgets/product_item.dart

You can get the job done as follows:

1. Add prefixes when importing:

// This one contains a class named ProductItem
import './widgets/product_item.dart'; 

// This one contains a class named ProductItem
import './providers/product_item.dart' as pPrefix;

// This one contains a class named ProductItem
import './models/product_item.dart' as mPrefix; 

2. Use classes with prefixes:

ProductItem() // the one without prefix
pPrefix.ProductItem() 
mPrefix.ProductItem()

That’s it. Further reading:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles