Menu
CoddyTech

Pass State to a Child

Part of the State Management section of Coddy's Flutter journey. Lesson 1 of 27.

An app is many widgets, and a small one often needs a value that a bigger one owns. Here the score lives in the page's State, but the board that shows it is a widget of its own.

To hand a value down, give the child a final field and ask for it in the constructor:

class ScoreBoard extends StatelessWidget {
  const ScoreBoard({super.key, required this.score});

  final int score;

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

The parent passes its value each time it builds the child: ScoreBoard(score: score). When the parent calls setState, it builds again, and the board gets the new number.

The child never changes the value. It shows what it was given, and the parent stays the one owner of the score.

challenge icon

Challenge

Easy

The +1 button counts points, but the board always says Score: 0.

  • Give ScoreBoard a final int score field, set by its constructor.
  • Make its text Score: followed by that score.
  • Pass the page's score when the page builds the board.

Try it yourself

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int score = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const ScoreBoard(),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  score++;
                });
              },
              child: const Text('+1'),
            ),
          ],
        ),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return const Text('Score: 0', style: TextStyle(fontSize: 32));
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in State Management

Practice on your own: Online Flutter compiler