CodeBlanks Logo Icon CodeBlanks

Periodic stream

Emit periodic values with Stream.periodic.

Stream.periodic

Stream.periodic creates a Stream that produces values at fixed intervals. The first parameter is a Duration, the second is a callback that produces each value.

Stream.periodic(Duration(seconds: 1), (count) => count);

count starts at 0 and increments each period.

Duration and callback

Duration determines how often Stream.periodic produces values. The callback receives the counter value each period and produces a result.

Stream.periodic(
  Duration(seconds: 2),
  (count) => count * 10,
)

The counter starts at 0 and increments each period.

Practice Produce a periodic stream with Stream.periodic

The sayiAkisi function should use Stream.periodic. It should produce twice the counter value every second. In main, call print('başladı').

Starter code

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

// sayiAkisi: periyodik akış üret

void main() {
  print('başladı');
}

Sample solution

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

Stream<int> sayiAkisi() {
  return Stream.periodic(Duration(seconds: 1), (sayac) => sayac * 2);
}

void main() {
  print('başladı');
}

Expected output

başladı

Questions and answers

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

1 What does Stream.periodic produce?

  • A single Future
  • A Widget
  • A Stream producing values at fixed intervals Correct answer
  • A List

Explanation: Stream.periodic creates a Stream that produces values at fixed Duration intervals; the callback is called each period.

2 Set Duration in seconds

Question
Stream.periodic(
  ____(seconds: 1),
  (sayac) => sayac,
)
Answer
Stream.periodic(
  Duration(seconds: 1),
  (sayac) => sayac,
)

Explanation: Stream.periodic's first parameter is Duration; it determines the production interval.

3 Stream.periodic parts

Term Meaning
Stream.periodic Stream producing periodic values
Duration Determines the period interval
sayac Value incrementing each period
callback Function producing each value

All lessons in Intermediate