CodeBlanks Logo Icon CodeBlanks

The build method

Learn what build returns and when it is called.

The build method

A StatelessWidget's build method produces the widget's appearance. It takes a BuildContext parameter and returns a Widget. Flutter calls build when the widget tree needs redrawing. build should be pure: no side effects, depending only on parameters.

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

When is build called?

build is called when the widget is first placed on screen and when its dependencies (Theme, MediaQuery) change. When a parent rebuilds, the child's build is called again too. So build must stay cheap; long tasks should not run inside build.

// build should depend on parameters
@override
Widget build(BuildContext context) {
  final theme = Theme.of(context);
  return Text('Merhaba', style: theme.textTheme.bodyLarge);
}

Practice Print build info

In main, print two lines with print: build donus Widget and build saf fonksiyon.

Starter code

main.dart
void main() {
  // iki satır yazdır:
  // build donus Widget
  // build saf fonksiyon

}

Sample solution

main.dart
void main() {
  print('build donus Widget');
  print('build saf fonksiyon');
}

Expected output

build donus Widget
build saf fonksiyon

Questions and answers

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

1 What does the build method return?

  • int
  • void
  • String
  • Widget Correct answer

Explanation: The build method returns a value of type Widget; this widget is drawn to the screen.

2 Return inside build

Question
Widget build(BuildContext context) {
  ____ Text('Selam');
}
Answer
Widget build(BuildContext context) {
  return Text('Selam');
}

Explanation: The build method returns a Widget with the return keyword.

3 build method concepts

Term Meaning
build Method returning a Widget
Widget Return type of build
return Keyword yielding a value
pure function Function without side effects

All lessons in Beginner