Skip to content

Instantly share code, notes, and snippets.

@osaxma
Last active January 9, 2022 14:04
Show Gist options
  • Save osaxma/d864144bf77c5217f7a00fa27e96de2a to your computer and use it in GitHub Desktop.
Save osaxma/d864144bf77c5217f7a00fa27e96de2a to your computer and use it in GitHub Desktop.
an example for stream provider
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Flutter Demo Home Page'),
),
body: const Center(
child: WidgetTop(),
),
),
);
}
}
class WidgetTop extends StatelessWidget {
const WidgetTop({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return StreamProvider<List<int>>(
create: (context) => numberStream(),
initialData: const [0],
child: const WidgetBottom(),
);
}
}
class WidgetBottom extends StatelessWidget {
const WidgetBottom({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final data = context.watch<List<int>>();
return Text(data.map((e) => e.toString()).reduce((value, element) => value + ',' + element));
}
}
// fake data stream
Stream<List<int>> numberStream() async* {
yield [0];
for (var i = 1; i < 50; i++) {
await Future.delayed(const Duration(seconds: 2));
yield [1, 2, 3].map((e) => e + i).toList();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment