Menu
CoddyTech

Send Data to a Screen

Part of the Lists and Screens section of Coddy's Flutter journey. Lesson 21 of 33.

A detail screen shows one item, the one you tapped. The screen is a widget, so it gets its data the way any widget does: through its constructor.

class PlanetScreen extends StatelessWidget {
  const PlanetScreen({super.key, required this.planet});

  final Planet planet;
  ...
}

The screen keeps the planet in a final field and reads it in build: Text(planet.name). super.key is the key every widget can take; keep it first.

Where you push the screen, pass the planet of the row that was tapped:

onTap: () {
  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => PlanetScreen(planet: planet)),
  );
},

One screen class now shows any planet. The list decides which one.

challenge icon

Challenge

Medium

Tap any planet: the screen always says Mercury. Make PlanetScreen show the planet that was tapped:

  • give it a final Planet planet; field and a required this.planet parameter
  • show planet.name in its app bar and Mars has 2 moons (with the planet's name and moons) in the middle
  • pass the tapped planet when you push it

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: HomeScreen(),
    );
  }
}

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

  final List<Planet> planets = const [
    Planet(name: 'Mercury', moons: 0),
    Planet(name: 'Venus', moons: 0),
    Planet(name: 'Earth', moons: 1),
    Planet(name: 'Mars', moons: 2),
    Planet(name: 'Jupiter', moons: 95),
    Planet(name: 'Saturn', moons: 146),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Planets')),
      body: ListView(
        children: [
          for (Planet planet in planets)
            ListTile(
              title: Text(planet.name),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => const PlanetScreen()),
                );
              },
            ),
        ],
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Mercury')),
      body: const Center(
        child: Text('Mercury has 0 moons'),
      ),
    );
  }
}

class Planet {
  final String name;
  final int moons;

  const Planet({required this.name, required this.moons});
}
quiz iconTest yourself

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

All lessons in Lists and Screens

Practice on your own: Online Flutter compiler