Constructors vs. Factories in Dart/Flutter
The Simple Rule
When you create an object from a class, you use a constructor. But sometimes, you need to do some work before you can even figure out what data to assign to your object's properties.
Constructors: Just Assign Data
Constructors should be "dumb". This means they should only take the data you provide when you create the object and assign that data directly to the class variables. Don't put complex calculations, data fetching, or other logic inside your main constructors.
Factories: Perfect for Smart Setup
This is where factory
constructors come in handy. If you need to do something clever or complicated to get the data you need before making an object (like fetching device info as shown in the image), a factory
constructor is the place to do it.
How Factories Work
A factory constructor doesn't necessarily create a new instance every time. It can perform actions (like getting data from the system) and then return an instance of the class, often using a standard constructor after the data is ready.
In Short
Keep your regular constructors lean – just data assignment. For any complex setup or data fetching before creating an object, use a factory constructor. This makes your code cleaner and easier to manage.