Widgets and StatelessWidget

Flutter · Essentials · 12 min

In Flutter everything on screen is a widget, so this mental model underlies every other lesson.

A widget is an immutable description of part of the UI: text, padding, a button, a whole screen. You build interfaces by composing small widgets into a tree: a Scaffold contains a Column, which contains Text and ElevatedButton widgets, and so on.

A `StatelessWidget` depends only on its constructor arguments. You override build(BuildContext context) and return a widget tree. Flutter calls build whenever the widget is inserted or its inputs change, and may call it often, so keep it fast and side-effect free.

Conventions:

  • Fields are final, and the constructor is const when possible: const Greeting({super.key, required this.name});. Passing super.key lets parents give the widget a key.
  • Child widgets go in child or children named parameters.
  • Extract a widget class when a build method grows; prefer new widget classes over helper methods returning widgets, since classes can be const and rebuild independently.

`BuildContext` is the widget's location in the tree. Use it to look up inherited data: Theme.of(context), MediaQuery.sizeOf(context), Navigator.of(context).

Because widgets are immutable and cheap, "changing" the UI means building new widgets with new values. Flutter diffs them against the previous tree and updates only what changed on screen.

Example

import 'package:flutter/material.dart';
class ProfileCard extends StatelessWidget {
  const ProfileCard({super.key, required this.name, this.role = 'Member'});

  final String name;
  final String role;

  @override
  Widget build(BuildContext context) {
    final textTheme = Theme.of(context).textTheme;   // inherited lookup
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(name, style: textTheme.titleLarge),
            Text(role, style: textTheme.bodySmall),
          ],
        ),
      ),
    );
  }
}
// Usage: const ProfileCard(name: 'Ana', role: 'Admin')

Remember

  • UIs are trees of small, immutable widgets
  • StatelessWidget = output depends only on constructor fields
  • Use const constructors and extract widget classes

Watch out for

  • Doing work with side effects (network calls, timers) inside build, which may run many times.

Check yourself

  1. What should a StatelessWidget's build method depend on?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.flutter.dev/ui