StreamBuilder는 무엇인가.... 우선 stream 은 흐름, 연속 등의 의미를 가지고 있다.
이 말의 의미로 보아, StreamBuilder는 연속적으로 무언가를 처리하는 것이 아닐까?
StreamBuilder를 찾아보던 중에 한 게시글에서 이 예제를 보게 되었는데, 간단하면서도 이해가 잘 되는 것 같다고 생각하여 그 코드를 보며 나도 코드를 작성해 보며 기능을 확인하였다.
코드는 이러하다.
bool _running = false;
Stream<String> clock() async* {
while (_running) {
await Future.delayed(const Duration(milliseconds: 200));
DateTime now = DateTime.now();
yield "${now.hour} : ${now.minute} : ${now.second}";
}
}
StreamBuilder(
stream: clock(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.toString());
} else {
return const Text('');
}
},
),
snapshot에는 FutureBuilder와 같이 connectionState, error, data 정보를 담고 있다.
ElevatedButton(
onPressed: () {
setState(() {
_running = true;
});
},
child: const Text('start'),
),
const SizedBox(
height: 20.0,
),
ElevatedButton(
onPressed: () {
setState(() {
_running = false;
});
},
child: const Text('stop'),
),