Classes and Objects in Flutter: A Relaxed Guide for Beginners Who Want to Get Good

If you’re just starting to explore Flutter, you’ve probably heard the terms class and object. These two concepts are the “heart” of object-oriented programming (OOP) used in Dart the language behind Flutter.
But don’t worry, we’ll go through this step-by-step so it’s easy to understand without making your head spin.

1. Why Should You Understand Classes and Objects in Flutter?

Flutter isn’t just about creating beautiful UIs it’s also about organizing your code so that it’s:

  • Clean
  • Readable
  • Easy to maintain

Classes and objects help us structure our code. For example, if you’re making a notes app, you could have:

  • Class to define the shape of a note
  • Object to represent each note

In real-world analogy:

  • Class = cookie mold
  • Object = cookie made from that mold

2. What is a Class in Dart/Flutter?

Simply put:

Class is a template or blueprint that describes how an object will be created.

Inside a class, we can have:

  • Properties (variables to store data)
  • Methods (functions the object can perform)
class Car {
  String brand;
  int year;

  // Constructor
  Car(this.brand, this.year);

  // Method
  void startEngine() {
    print('$brand year $year: Engine started!');
  }
}

3. What is an Object in Dart/Flutter?

An object is the actual result of a class. If we have a Car class, we can create an object like this:

void main() {
  var myCar = Car('Toyota', 2020);
  myCar.startEngine(); // Output: Toyota year 2020: Engine started!
}

4. Why Does Flutter Need Classes and Objects?

Because almost every widget in Flutter is a class. For example, Text, Column, Row, Scaffold  they are all classes that we instantiate into objects when we use them.

Text('Hello World')

Here, Text is a class, and 'Hello World' is the data we pass to its constructor to create a Text object.

5. Creating a Class in Flutter

Usually, classes in Flutter are used for:

  1. Data models (e.g., user, product, note)
  2. Helpers (utility logic)
  3. Custom widgets
class User {
  String name;
  String email;

  User({required this.name, required this.email});

  void greet() {
    print('Hi, my name is $name and my email is $email');
  }
}

6. Creating an Object from a Class

void main() {
  var user1 = User(name: 'Alex', email: 'alex@example.com');
  user1.greet();
}

7. Constructors in Dart

Constructors are special functions that run when an object is created.

Default Constructor

class Book {
  String title;
  Book(this.title);
}

Named Constructor

class Book {
  String title;
  Book(this.title);

  Book.empty() : title = 'Untitled';
}

Factory Constructor

class Book {
  String title;
  Book(this.title);

  factory Book.fromMap(Map<String, dynamic> data) {
    return Book(data['title']);
  }
}

8. Properties and Methods

class Animal {
  String name;
  int age;

  Animal(this.name, this.age);

  void makeSound() {
    print('$name makes a sound...');
  }
}

9. Encapsulation (Data Hiding)

In Dart, we can protect a property by making it private (prefix it with _).

class BankAccount {
  double _balance = 0;

  void deposit(double amount) {
    _balance += amount;
  }

  double checkBalance() {
    return _balance;
  }
}

10. Inheritance

class Animal {
  void eat() => print('Animal is eating');
}

class Cat extends Animal {
  void meow() => print('Meooow!');
}

void main() {
  var kitty = Cat();
  kitty.eat();
  kitty.meow();
}

11. Polymorphism

class Animal {
  void makeSound() => print('Animal makes a sound');
}

class Cat extends Animal {
  @override
  void makeSound() => print('Meooow!');
}

12. Abstract Class

abstract class Vehicle {
  void startEngine();
}

class Motorcycle extends Vehicle {
  @override
  void startEngine() => print('Motorcycle started');
}

13. Class as a Widget in Flutter

import 'package:flutter/material.dart';

class ProductCard extends StatelessWidget {
  final String name;
  final int price;

  const ProductCard({super.key, required this.name, required this.price});

  @override
  Widget build(BuildContext context) {
    return Card(
      child: ListTile(
        title: Text(name),
        subtitle: Text('Rp $price'),
      ),
    );
  }
}

14. Tips for Learning Classes and Objects in Flutter

  • Start with simple data models
  • Learn constructors and named constructors
  • Get used to separating logic from UI using classes
  • Use inheritance wisely
  • Use private properties (_) when necessary

Classes and objects in Flutter/Dart are like the foundation of a house. If the foundation is strong, your app will be:

  • Easier to develop
  • More organized
  • Better structured


0 Comments:

Post a Comment