9.4 C
New York
Saturday, December 2, 2023

Flutter: Using same-name classes imported from different files

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.Advertisements

.
??? 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()

AdvertisementsThatÂ’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.

Related Articles

Latest Articles