Created with <3 with dartpad.dev.
Created
June 2, 2023 12:09
-
-
Save vipulshah2010/50c932cbe6965e923fd5c17914b1d789 to your computer and use it in GitHub Desktop.
exquisite-snowflake-4839
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 'dart:math'; | |
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(const MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({super.key}); | |
// This widget is the root of your application. | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Streams Demo', | |
theme: ThemeData( | |
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), | |
useMaterial3: true, | |
), | |
home: const MyHomePage(title: 'Streams'), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
const MyHomePage({super.key, required this.title}); | |
final String title; | |
@override | |
State<MyHomePage> createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
int _futureValue = 0; | |
late StreamSubscription subscription; | |
void _startListen() { | |
subscription = getRandomValues().listen((value) { | |
setState(() { | |
_futureValue = value; | |
}); | |
}); | |
} | |
void _stopListen() { | |
subscription.cancel(); | |
setState(() { | |
_futureValue = 0; | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
backgroundColor: Theme.of(context).colorScheme.inversePrimary, | |
title: Text(widget.title), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
Text( | |
'$_futureValue', | |
style: Theme.of(context).textTheme.headlineMedium, | |
), | |
ElevatedButton( | |
child: const Text('Start Listening'), | |
onPressed: () => _startListen(), | |
), | |
ElevatedButton( | |
child: const Text('Stop Listening'), | |
onPressed: () => _stopListen(), | |
), | |
], | |
), | |
) // This trailing comma makes auto-formatting nicer for build methods. | |
); | |
} | |
Stream<int> getRandomValues() async* { | |
var random = Random(); | |
while (true) { | |
await Future.delayed(const Duration(seconds: 1)); | |
yield random.nextInt(100); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment