A Flutter app is a tree of widgets. runApp takes the top widget and puts it on the screen. MaterialApp gives your app Google's Material Design look.
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(
home: Scaffold(
appBar: AppBar(title: const Text('CodeChallenge')),
body: const Center(child: Text('Hello, Flutter!')),
),
);
}
}Widgets you will use every day
Scaffoldis the basic page: it has slots for anappBar, abodyand more.Textshows text. Change its look withstyle: TextStyle(...).Centerputs itschildin the middle of the space it has.- Most widgets take one
childor a list ofchildren.
Your own widgets
When part of a screen repeats or grows big, move it into its own class. A StatelessWidget gets its data from its constructor and describes the screen in build.
Run the app with flutter run. Save a file and hot reload shows your change in about a second, without losing your place in the app.
Code examples
class Greeting extends StatelessWidget {
const Greeting({super.key, required this.name});
final String name;
@override
Widget build(BuildContext context) {
return Text(
'Hello, $name!',
style: const TextStyle(fontSize: 24),
);
}
}
// Use it anywhere: const Greeting(name: 'Dara')Expected output
The text "Hello, Dara!" in large letters.
required this.name makes the name parameter mandatory, so Greeting() without a name will not compile.
Common mistakes
Common mistake: Forgetting `return` in build
build must return a widget. Without return, Dart reports that the method can't return null.
Common mistake: Keeping changing values in a StatelessWidget
A StatelessWidget can't update itself. Use a StatefulWidget when the screen must change (see the next lessons).
Check your understanding
3 quick questions about this lesson.