Skip to content

Instantly share code, notes, and snippets.

@fonkamloic
Created October 26, 2021 20:41
Show Gist options
  • Save fonkamloic/29523f0eec0a13d978b62a48179056a9 to your computer and use it in GitHub Desktop.
Save fonkamloic/29523f0eec0a13d978b62a48179056a9 to your computer and use it in GitHub Desktop.
Experimenting on Stream with isolates in flutter
import 'dart:async';
import 'dart:isolate';
import 'package:flutter/material.dart';
void computeIsolate(Message message) {
Stream<int> streamcompute(numb) async* {
for (var i = 0; i < numb; i++) {
yield i;
}
}
final StreamController _controller = StreamController.broadcast();
_controller.addStream(streamcompute(message.numb));
_controller.stream.listen((event) {
message.sendPort.send(event);
});
// streamcompute(message.numb).listen((event) {
// message.sendPort.send(event);
// });
}
void main() async {
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: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
final receivePort = ReceivePort();
Isolate? isolate;
List list = <ListTile>[];
@override
void initState() {
super.initState();
Future.microtask(() async {
isolate = await Isolate.spawn(
computeIsolate,
Message(sendPort: receivePort.sendPort, numb: 20),
);
list = [];
receivePort.listen((message) {
print(message);
}).onData((data) {
list.add(ListTile(
title: Text("First message from isolate stream is $data")));
});
});
}
@override
void dispose() {
isolate?.kill();
super.dispose();
}
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
Container(
height: 700,
alignment: Alignment.center,
child: ListView.builder(
itemCount: 20,
itemBuilder: (context, index) {
if (list.isNotEmpty) {
return list[index];
} else {
return const Text('isolate did not run');
}
},
),
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class Message {
Message({
required this.numb,
required this.sendPort,
});
int numb;
SendPort sendPort;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment