Skip to content

Instantly share code, notes, and snippets.

@terryl1900
Last active July 21, 2022 23:29
Show Gist options
  • Save terryl1900/ce8adc72010fc274f217b43d6304c331 to your computer and use it in GitHub Desktop.
Save terryl1900/ce8adc72010fc274f217b43d6304c331 to your computer and use it in GitHub Desktop.
Counter app with stream
import 'dart:async';
import 'package:flutter/material.dart';
// A counter app using Stream to manage state.
// counter.dart
int _count = 0;
final _controller = StreamController<int>()..add(_count);
Stream<int> counter() => _controller.stream;
void increment() => _controller.add(_count++);
void decrement() => _controller.add(_count--);
// main.dart
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Counter example')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
StreamBuilder<int>(
stream: counter(),
builder: (context, snapshot) => Text('${snapshot.data}'),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextButton(
onPressed: () => increment(), child: const Text('+1')),
TextButton(
onPressed: () => decrement(), child: const Text('-1')),
],
),
],
),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment