iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

StatelessWidget

A StatelessWidget is a pure function of its constructor arguments. It can’t hold state — if you need state, use StatefulWidget. Stateless widgets are cheap to rebuild and easy to reason about.

Three stateless widgets

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

// 1. Pure presentation
class Greeting extends StatelessWidget {
    final String name;
    final Color  color;
    const Greeting({super.key, required this.name, this.color = Colors.green});

    @override
    Widget build(BuildContext context) {
        return Text('Hello, $name',
            style: TextStyle(color: color, fontSize: 22, fontWeight: FontWeight.bold));
    }
}

// 2. Composition — wrap children with padding + Card
class Tile extends StatelessWidget {
    final String title;
    final Widget child;
    const Tile({super.key, required this.title, required this.child});

    @override
    Widget build(BuildContext context) {
        return Card(
            child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                        Text(title, style: Theme.of(context).textTheme.titleMedium),
                        const SizedBox(height: 8),
                        child,
                    ],
                ),
            ),
        );
    }
}

// 3. A page (still stateless if all state lives elsewhere)
class HomePage extends StatelessWidget {
    const HomePage({super.key});
    @override
    Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(title: const Text('Home')),
            body: const Center(child: Greeting(name: 'Flutter')),
        );
    }
}

Why it matters

Use const constructors on everything you can. Flutter re-uses const widget instances across rebuilds — one of the cheapest performance wins.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
class Greet extends StatelessWidget {
    final String name;
    const Greet({super.key, required this.name});
    @override
    Widget build(BuildContext context) => Text('Hello, $name');
}
Try it Yourself »

Exercise

Base class for a widget with no state.

class Greet extends Widget {}

Discussion

Loading…