Dumb and smarter

Flutter tips Published on

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.

Save 3 months of work

Create your app using our 6 years of making Flutter apps and more than 50+ apps

kickstarter for flutter apps

Frequently Asked Questions

What should a regular constructor do?

It should primarily focus on assigning the data passed to it to the class properties.

What is the purpose of a factory constructor?

Factory constructors are used for more complex logic or setup needed before an object can be created, such as fetching data or performing calculations.

Can I put complex logic in a regular constructor?

It's recommended to keep regular constructors simple and only handle data assignment. Complex logic should go into a factory constructor.

Read more
You may also be interested in
Published on
Draw text on a canvas  blog card image
Draw text on a canvas
Published on 2025-05-12T09:29:00.038Z
ApparenceKit is a flutter template generator tool by Apparence.io © 2025.
All rights reserved