Last active
August 27, 2024 02:47
-
-
Save slightfoot/21ae293ace36eff266d333a6c87c487f to your computer and use it in GitHub Desktop.
Streaming Text in Flutter
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'; | |
void main() => | |
runApp(MaterialApp( | |
home: ExampleScreen(), | |
)); | |
class ExampleScreen extends StatelessWidget { | |
Stream<String> _loadData() async* { | |
StringBuffer buffer = StringBuffer(); | |
for (int i = 0; i < 20; i++) { | |
await Future.delayed(Duration(seconds: 1)); | |
buffer.writeln("Line ${i}"); | |
yield buffer.toString(); | |
} | |
} | |
@override | |
Widget build(BuildContext context) { | |
return new Scaffold( | |
body: SafeArea( | |
child: StreamBuilder<String>( | |
stream: _loadData(), | |
builder: (BuildContext context, AsyncSnapshot<String> snapshot) { | |
if (snapshot.hasData) { | |
return Padding( | |
padding: const EdgeInsets.all(8.0), | |
child: Text(snapshot.data), | |
); | |
} else { | |
return Center(child: CircularProgressIndicator()); | |
} | |
}, | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! This is a great, easy-to-follow example