CodeBlanks Logo Icon CodeBlanks

const and ListView.builder

Learn the performance impact of const widgets and builders.

const widget

const widgets are created at compile time and are not recreated during rebuild. This avoids unnecessary build and paint work. const Text('Merhaba') uses the same object every frame.

const Text('Merhaba')
// same object every rebuild

ListView.builder

ListView.builder only builds the items visible on screen; for long lists it is much more efficient than ListView. It takes itemCount and itemBuilder parameters.

ListView.builder(
  itemCount: 1000,
  itemBuilder: (context, index) => Text('$index'),
)

Practice Create a ListView.builder

In main, create a ListView.builder widget: itemCount: 10, itemBuilder: (context, i) => Text('$i'). Print the widget's runtimeType.

Starter code

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

void main() {
  // ListView.builder oluştur: itemCount 10, itemBuilder (context, i) => Text('$i')
  // runtimeType yazdır
}

Sample solution

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

void main() {
  final widget = ListView.builder(
    itemCount: 10,
    itemBuilder: (context, i) => Text('$i'),
  );
  print(widget.runtimeType);
}

Expected output

ListView

Questions and answers

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

1 When is a const widget created?

  • Anew on every rebuild
  • Never
  • At compile time, reused on rebuild Correct answer
  • Only at runtime

Explanation: A const widget is created once at compile time; during rebuild the same object is reused, so build and paint cost drops to zero.

2 Use ListView.builder

Question
ListView.____(itemCount: 100, itemBuilder: (context, i) => Text('$i'))
Answer
ListView.builder(itemCount: 100, itemBuilder: (context, i) => Text('$i'))

Explanation: ListView.builder builds only the visible items; separated is for lists with dividers, custom for sliver-based lists.

3 const and ListView.builder matches

Term Meaning
const Compile-time constant
ListView List widget
builder Builds visible items
itemCount Total item count

All lessons in Expert