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:
- Inheritance in Dart: A Quick Example
- Dart: How to Remove or Replace Substrings in a String
- Flutter & Hive Database: CRUD Example
- Flutter: Making Beautiful Chat Bubbles (2 Approaches)
- Flutter: Search field with magnifying glass inside
- Using Chip widget in Flutter: Tutorial & Examples
You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.