프로그래밍 공부 메모/flutter

StreamBulider<T> 스트림 빌더

jjs815 2022. 7. 14. 00:03
import 'package:flutter/material.dart';

class Counter extends StatefulWidget {
  const Counter({super.key});

  @override
  State<Counter> createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  final int price = 2000;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Stream builder'),
      ),
      body: StreamBuilder<int>(
        initialData: price,
        stream: addStreamValue(), //addStreamValue()를 구독하고 있는 느낌
        builder: (context, snapshot) {
          //snapshot -> 스트림의(addStreamValue 메서드) 결과물
          final priceNumber = snapshot.data.toString();
          return Center(
            child: Text(
              priceNumber,
              style: TextStyle(
                fontSize: 40,
                fontWeight: FontWeight.bold,
                color: Colors.blue,
              ),
            ),
          );
        },
      ),
    );
  }

  Stream<int> addStreamValue() {
    return Stream<int>.periodic(Duration(seconds: 1),
        (count) => price + count); //period일정 간격 으로 이벤트를 반복적으로 내보내는 스트림을 만듭니다 .
  }
}
반응형