Skip to content

Instantly share code, notes, and snippets.

@dnys1
Last active October 1, 2021 03:43
Show Gist options
  • Save dnys1/8604e7ee9bcc71626251b162b00344ca to your computer and use it in GitHub Desktop.
Save dnys1/8604e7ee9bcc71626251b162b00344ca to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
// Native
// Pretend this is the native side emitting progress.
Stream<double> get nativeProgressEmitter async* {
var progress = 0.0;
while (progress < 1) {
yield progress;
progress += Random().nextDouble() / 3;
await Future.delayed(const Duration(milliseconds: 500));
}
yield 1;
}
// Our API (amplify_storage_s3)
// Just demonstrating the StreamSink usage, so the rest is commented out.
Future<void /* UploadFileResult */ > uploadFile({
// required String key,
// required File local,
// UploadFileOptions? options,
StreamSink<double>? progressSink,
}) async {
// Event channel stuff. Get stream from platform.
final eventChannelStream = nativeProgressEmitter.asBroadcastStream();
progressSink?.addStream(eventChannelStream);
await eventChannelStream.last;
// return result
}
// User's App
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Progress Listener',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Stream<double>? _uploadProgress;
bool _isFinished = false;
@override
void initState() {
super.initState();
_uploadFile();
}
Future<void> _uploadFile() async {
final StreamController<double> _controller = StreamController(sync: true);
setState(() {
_uploadProgress = _controller.stream;
});
await uploadFile(progressSink: _controller.sink);
setState(() {
_isFinished = true;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Progress Listener'),
),
body: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 300),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'Uploading file:',
),
const SizedBox(height: 10),
if (_isFinished)
const Icon(
Icons.check_circle,
color: Colors.green,
size: 40,
)
else
StreamBuilder<double>(
stream: _uploadProgress,
builder: (context, snapshot) {
return LinearProgressIndicator(value: snapshot.data ?? 0);
},
),
],
),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment