0
0
Fluttermobile~5 mins

Classes and objects in Flutter

Choose your learning style9 modes available
Introduction

Classes help you organize your app by grouping related data and actions together. Objects are like real things made from these blueprints.

When you want to represent a real-world thing like a user or a product in your app.
When you need to keep data and the actions on that data together in one place.
When you want to create many similar items with different details easily.
When your app grows and you want to keep your code neat and easy to understand.
Syntax
Flutter
class ClassName {
  // properties
  Type propertyName;

  // constructor
  ClassName(this.propertyName);

  // method
  void methodName() {
    // code
  }
}

// Creating an object
var objectName = ClassName(value);

Use class keyword to define a class.

Constructor sets initial values when you create an object.

Examples
This defines a Person class with name and age. The sayHello method prints a greeting.
Flutter
class Person {
  String name;
  int age;

  Person(this.name, this.age);

  void sayHello() {
    print('Hello, my name is $name.');
  }
}

var p = Person('Anna', 25);
p.sayHello();
This Car class has a brand and a method to honk.
Flutter
class Car {
  String brand;

  Car(this.brand);

  void honk() {
    print('$brand says Beep!');
  }
}

var myCar = Car('Toyota');
myCar.honk();
Sample App

This Flutter app shows how to create a Person object and display a greeting using its method.

Flutter
import 'package:flutter/material.dart';

class Person {
  String name;
  int age;

  Person(this.name, this.age);

  String greet() {
    return 'Hi, I am $name and I am $age years old.';
  }
}

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    var person = Person('Liam', 30);

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Classes and Objects')),
        body: Center(
          child: Text(person.greet(), style: const TextStyle(fontSize: 20)),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Objects are created from classes using constructors.

Methods inside classes define what actions the object can do.

Use clear names for classes and properties to keep code readable.

Summary

Classes are blueprints for creating objects.

Objects hold data and can perform actions defined by their class.

Using classes helps organize and reuse code in your app.