Flutter
Reusability
Reuse the same widget across screens.
Reusability
You can write a custom widget once and use it across many screens. The same Baslik class can appear in both AnaEkran and ProfilEkran; this prevents code duplication and ensures consistency. By placing the widget in a separate file and pulling it with import, you share it across the project.
class Baslik extends StatelessWidget {
final String yazi;
const Baslik({super.key, required this.yazi});
@override
Widget build(BuildContext context) => Text(yazi);
}
class AnaEkran extends StatelessWidget {
const AnaEkran({super.key});
@override
Widget build(BuildContext context) => Baslik(yazi: 'Ana');
}
Defining a widget in a separate file
After placing a widget in its own file, you add import 'file_path.dart'; at the top of the file where you want to use it. Dart treats the file name as a library name. This way you access the same widget class across the project.
// widgets/baslik.dart
class Baslik extends StatelessWidget {
// ...
}
// ekrana_ekran.dart
import 'widgets/baslik.dart';
class AnaEkran extends StatelessWidget {
// Baslik is available here
}
Exercise Reuse the Baslik widget
Define a StatelessWidget named Baslik with a required final String yazi field whose build method returns Text(yazi). Then define another StatelessWidget named AnaEkran whose build method returns Baslik(yazi: 'Ana'). Print 'hazir' in main.
Show example solution
import 'package:flutter/widgets.dart';
class Baslik extends StatelessWidget {
final String yazi;
const Baslik({super.key, required this.yazi});
@override
Widget build(BuildContext context) {
return Text(yazi);
}
}
class AnaEkran extends StatelessWidget {
const AnaEkran({super.key});
@override
Widget build(BuildContext context) {
return Baslik(yazi: 'Ana');
}
}
void main() {
print('hazir');
}
Test yourself
-
What do you do to use a widget in another file?
- Call http.get
- Call jsonDecode
- Rewrite the widget
- Pull the file with import
Show answer
Pull the file with import — To use a widget in a separate file you import that file. Rewriting causes duplication, http.get is a network request, and jsonDecode is for decoding JSON; none of these share files.
-
Import the file
// ana_ekran.dart
____
class AnaEkran extends StatelessWidget {
// Baslik burada kullanılır
}
Show answer
// ana_ekran.dart
import 'widgets/baslik.dart'
class AnaEkran extends StatelessWidget {
// Baslik burada kullanılır
}
-
Reusability parts
- import
- File import
- ayrı dosya
- The widget's library
- aynı sınıf
- Used across many screens
- kod tekrarı
- The avoided problem
Next lesson: Summary - Custom widget