Summary - StatelessWidget
- Flutter course
- Beginner
- Lesson 20/99
- 4 min
Combine StatelessWidget, build and const to write a static card.
StatelessWidget summary
A StatelessWidget is an immutable, stateless widget that receives data via constructor parameters. Its build method returns a Widget based only on parameters and context. Making the constructor const merges instances with the same params into a single canonical object, boosting performance. Combining the three lets you build static cards, labels and titles.
class Kart extends StatelessWidget {
final String baslik;
const Kart({super.key, required this.baslik});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(baslik),
);
}
}Practice Write the Kart class and run
First print print('kart hazir'), then call runApp(MaterialApp(home: Kart(baslik: 'Merhaba'))). Also define a Kart class extending StatelessWidget, with a final String baslik field, a const constructor, and a build method returning Text(baslik).
Starter code
import 'package:flutter/material.dart';
void main() {
// 'kart hazir' mesajını print ile yazdır
// runApp ile MaterialApp çağır; home Kart widget'ı olsun
}
// Kart sınıfını tanımla
// StatelessWidget'dan extends etsin
// final String baslik alsın, const kurucu required ile
// build metodu Text(baslik) döndürsünSample solution
import 'package:flutter/material.dart';
void main() {
print('kart hazir');
runApp(MaterialApp(home: Kart(baslik: 'Merhaba')));
}
class Kart extends StatelessWidget {
final String baslik;
const Kart({super.key, required this.baslik});
@override
Widget build(BuildContext context) {
return Text(baslik);
}
}Expected output
kart hazir
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the extends keyword do?
- Overrides a method
- Declares a variable
- Inherits from a class Correct answer
- Implements an interface
Explanation: extends lets a class inherit fields and methods from another class; Kart extends StatelessWidget.
2 Extend the class
class Kart ____ StatelessWidget {
final String baslik;
const Kart({super.key, required this.baslik});
}
class Kart extends StatelessWidget {
final String baslik;
const Kart({super.key, required this.baslik});
}
Explanation: extends provides inheritance from StatelessWidget.
3 StatelessWidget combined
| Term | Meaning |
|---|---|
StatelessWidget kalıbı |
Stateless widget template |
final alan |
Immutable outside constructor |
const kurucu |
Produces a canonical instance |
extends |
Inherits from StatelessWidget |