CodeBlanks Logo Icon CodeBlanks

What is a custom widget?

Write your own widget as a StatelessWidget.

What is a custom widget?

A custom widget is a StatelessWidget subclass that you define. You override the build method to draw the interface you want. You write it once and use it in many places.

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

  @override
  Widget build(BuildContext context) {
    return const Text('Merhaba');
  }
}

Adding a const constructor lets the widget sit as a constant in the widget tree and improves performance.

The build method and Widget return

The build method must return a Widget. Flutter draws this widget on screen. The method signature is Widget build(BuildContext context); context represents the position in the widget tree.

@override
Widget build(BuildContext context) {
  return const Padding(
    padding: EdgeInsets.all(8),
    child: Text('Selam'),
  );
}

The returned widget can be a simple Text or a deep tree nesting many widgets.

Practice Define BaslikWidget

Define a StatelessWidget named BaslikWidget. Add a const constructor and have the build method return Text('Merhaba'). Print 'hazir' in main.

Starter code

main.dart
import 'package:flutter/widgets.dart';

// BaslikWidget adında StatelessWidget tanımla
// const constructor ekle
// build metodu bir Text widget'ı döndürsün

void main() {
  // 'hazir' yazdır
}

Sample solution

main.dart
import 'package:flutter/widgets.dart';

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

  @override
  Widget build(BuildContext context) {
    return const Text('Merhaba');
  }
}

void main() {
  print('hazir');
}

Expected output

hazir

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the correct way to define a custom widget?

  • Call http.get
  • Write a function returning a Future
  • Extend StatelessWidget and override the build method Correct answer
  • Create an sqflite table

Explanation: A custom widget is a class that extends StatelessWidget and overrides the build method. A Future function is for async work, sqflite is a database, and http.get is a network request; none of these define a widget.

2 Extend StatelessWidget

Question
class Baslik ____ {
  const Baslik({super.key});

  @override
  Widget build(BuildContext context) {
    return const Text('Merhaba');
  }
}
Answer
class Baslik extends StatelessWidget {
  const Baslik({super.key});

  @override
  Widget build(BuildContext context) {
    return const Text('Merhaba');
  }
}

Explanation: A custom widget extends StatelessWidget. StatefulWidget is for stateful widgets, implements Widget is a wrong interface, and Container is a widget that cannot be extended.

3 Custom widget parts

Term Meaning
class Baslik Class declaration
extends StatelessWidget Inheritance
build metodu UI rendering
const constructor Const constructor

All lessons in Intermediate