0
0
Fluttermobile~5 mins

Constructors and named parameters in Flutter

Choose your learning style9 modes available
Introduction

Constructors create objects from classes. Named parameters make it easy to set values clearly when creating objects.

When you want to create a new screen or widget with specific settings.
When you want to pass data to a widget in a clear way.
When you want to make some parameters optional or required.
When you want your code to be easier to read and understand.
When you want to avoid mistakes by naming parameters explicitly.
Syntax
Flutter
class MyWidget extends StatelessWidget {
  final String title;
  final int count;

  MyWidget({required this.title, this.count = 0});

  @override
  Widget build(BuildContext context) {
    return Text('$title: $count');
  }
}

Use curly braces { } to define named parameters.

Use required keyword to make a named parameter mandatory.

Examples
This constructor requires name but age is optional with default 18.
Flutter
class Person {
  String name;
  int age;

  Person({required this.name, this.age = 18});
}
Create a Person object with name 'Anna' and default age 18.
Flutter
var p = Person(name: 'Anna');
Create a Person object with name 'Bob' and age 25.
Flutter
var p = Person(name: 'Bob', age: 25);
Sample App

This app shows a greeting message using named parameters in the constructor. The message parameter is optional and defaults to 'Hello'.

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

class Greeting extends StatelessWidget {
  final String name;
  final String message;

  Greeting({required this.name, this.message = 'Hello'});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('$message, $name!', style: TextStyle(fontSize: 24)),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Greeting(name: 'Alice'),
    ),
  ));
}
OutputSuccess
Important Notes

Named parameters improve code readability by showing what each value means.

Use default values to make parameters optional.

Always mark important parameters as required to avoid errors.

Summary

Constructors create objects from classes.

Named parameters use curly braces and can be optional or required.

They make your code easier to read and safer.