Learn/Dart for Flutter/Classes & Objects

Classes & Objects

Object-oriented programming basics

6 min~5 min read+35 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Named Constructors
  2. 2. Getters & Setters
  3. 3. Writing Better Model Classes
  4. 4. This Lesson In Simple Words
  5. 5. Your level focus
  6. 6. One practical habit
  7. 7. Deep Understanding Guide
  8. 8. Why this lesson matters
  9. 9. Study flow for better retention
  10. 10. Quick Glossary

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Classes in Dart

Classes are blueprints for creating objects. Everything in Flutter is built using classes, so understanding them is essential.

dart
1class User {
2 // Properties (fields)
3 String name;
4 int age;
5
6 // Constructor
7 User(this.name, this.age);
8
9 // Method
10 void sayHello() {
11 print('Hi, I am $name');
12 }
13}
14
15// Using the class
16var user = User('John', 25);
17print(user.name); // John
18user.sayHello(); // Hi, I am John

Named Constructors

Dart allows you to create multiple constructors for a class using named constructors. This is useful when you need different ways to create the same type of object.

dart
1class User {
2 String name;
3 int age;
4
5 // Default constructor
6 User(this.name, this.age);
7
8 // Named constructor
9 User.guest() : name = 'Guest', age = 0;
10
11 // Named constructor from JSON (very common!)
12 User.fromJson(Map<String, dynamic> json)
13 : name = json['name'],
14 age = json['age'];
15}
16
17var guest = User.guest();
18var fromApi = User.fromJson({'name': 'Jane', 'age': 30});

Flutter Uses This Pattern

💡 Flutter Uses This Pattern

`User.fromJson()` is how you convert API responses to Dart objects. You will use this pattern frequently.

Getters & Setters

Getters and setters let you control access to an object's properties. They allow you to add logic when reading or writing a value.

dart
1class Rectangle {
2 double _width;
3 double height;
4
5 Rectangle(this._width, this.height);
6
7 // Getter - read the private field
8 double get width => _width;
9
10 // Getter - computed property
11 double get area => _width * height;
12
13 // Setter with validation
14 set width(double value) {
15 if (value > 0) _width = value;
16 }
17}
18
19var rect = Rectangle(10, 5);
20print(rect.area); // 50.0

Writing Better Model Classes

Model classes should be easy to create, validate, and maintain:

  • Prefer immutable fields (final) where possible
  • Add fromJson and toJson for API boundaries
  • Keep validation close to constructor or factory methods
  • Use getters for computed values, not duplicated stored fields
  • Keep UI formatting logic out of model classes

Strong model design prevents scattered data bugs later in larger projects.

OOP Practice Tasks

  • Build a Product model with fromJson and toJson methods.
  • Add one computed getter like discountedPrice.
  • Add validation to reject invalid constructor input.
  • Create a named constructor for guest or default state.

This Lesson In Simple Words

Object oriented programming basics. Dart is the language behind Flutter, and clear Dart code makes your Flutter UI easier to maintain.

Your level focus

Build confidence with basics first; speed comes later.

One practical habit

Prefer readable names, explicit intent, and async/await over deeply nested callbacks.

Deep Understanding Guide

Why this lesson matters

When Dart basics are weak, state bugs, null crashes, and async confusion increase quickly.

Study flow for better retention

  1. Read one section, run one tiny example, then explain the idea in your own words.
  2. Treat each Dart concept as a building block for widgets, services, and tests you will write later.
  3. If you can teach it in 45 seconds without notes, you understood it.

Common Mistakes To Avoid

  • Ignoring null safety and forcing values with ! without checking data flow.
  • Writing long functions that mix validation, transformation, and side effects together.
  • Using dynamic where a proper type would catch mistakes earlier.
  • Catching broad errors without keeping useful context for debugging.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Write a small pure function and test it with edge cases.
  • Convert one callback-based snippet to async/await with proper error handling.
  • Refactor a long function into smaller helper methods with clear names.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What does `this.name` in constructor mean?".

Quick Glossary

  • validation: Checks that confirm input is correct before processing.
  • const: A compile-time constant that can reduce rebuild work.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Lesson Completion Checklist

  • I can explain "Classes & Objects" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Ignoring null safety and forcing values with ! without checking data flow.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What does `this.name` in constructor mean?

this.name is shorthand for this.name = name in the constructor.

What is User.fromJson() called?

Named constructors use ClassName.name() syntax.

What does this getter return?

The getter computes area as width * height = 5 * 3 = 15.

How do you make a property private in Dart?

Dart uses _ prefix for library-private members. There is no private keyword.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue