Working with widgets

June 13, 2025

Overview

  • Base Code
  • Add Button

Add a button

Now that you’ve reviewed whats happening in lib/main.dart add a button after the text in the column widget.

The code for the button to be added looks like this.

ElevatedButton(
  child: const Text('Click Me'),
  onPressed: () {
    print('button pressed!');
  },
)

Add the button code above as a child in the column, after the Text('Hello $name'), widget definition.

The button definition uses an ElevatedButton widget which has a required child: parameter, where you’re supplying a Text widget displaying the words “Click Me”. Finally for the onPressed: parameter you’ve defined an anonymous function that prints “button pressed” to the console.

The whole MyHomePage widget class should look like the following

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

  final name = "World";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Text('Hello $name'),
          ElevatedButton(
            child: const Text('Click Me'),
            onPressed: () {
              print('button pressed!');
            },
          )
        ],
      ),
    );
  }
}

Launch your application with the steps you learned earlier to see the button in action.