Last active
July 21, 2022 23:29
-
-
Save terryl1900/ce8adc72010fc274f217b43d6304c331 to your computer and use it in GitHub Desktop.
Counter app with stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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