Menu
CoddyTech

A Widget Class of Your Own

Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 9 of 34.

Every widget you have used, Text, Row, Scaffold, is a class someone wrote. You can write your own, and you already have one: MyApp.

From here on your apps have two classes. MyApp sets up the app with MaterialApp, and the screen gets a class of its own, HomePage:

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: Text('Hi')),
    );
  }
}

extends StatelessWidget makes HomePage a widget. The const HomePage({super.key}); line is what lets you write HomePage(): copy it as it is, with your class's name. build returns what the widget shows.

Use it like any other widget: home: HomePage(). A screen in its own class is easier to read, and in the next lessons it lets the screen change while the app around it stays the same.

challenge icon

Challenge

Easy

The HomePage class is written at the bottom of the file, but the app still shows its old Coming soon screen.

  • Give the Scaffold in HomePage an AppBar titled Notes.
  • Make MyApp show it: replace the whole Scaffold after home: with HomePage().

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 MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(child: Text('Coming soon')),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: Text('No notes yet')),
    );
  }
}
quiz iconTest yourself

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

All lessons in Making It Interactive

Practice on your own: Online Flutter compiler