Skip to content

Instantly share code, notes, and snippets.

@Maxibond
Created February 2, 2020 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Maxibond/46e923ce8b665090250ca2f31d27d1eb to your computer and use it in GitHub Desktop.
Save Maxibond/46e923ce8b665090250ca2f31d27d1eb to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
class Progress extends StatefulWidget {
Progress({Key key, this.durationInMs = 5000}) : super(key: key);
final int durationInMs;
final double width = 300;
final double height = 20;
@override
_ProgressState createState() => _ProgressState();
}
class _ProgressState extends State<Progress> {
bool done = false;
bool inProgress = false;
int donePercentage = 0;
Timer t;
void _runProgress() {
if (inProgress) {
return;
}
setState(() {
inProgress = true;
done = false;
});
Duration period = Duration(milliseconds: (widget.durationInMs / 100).round());
print("Period: $period");
t = Timer.periodic(period, (timer) {
if (donePercentage >= 100 || inProgress == false) {
t.cancel();
}
setState(() {
t = timer;
donePercentage = min(donePercentage + 1, 100);
done = donePercentage == 100;
});
});
}
void _stopProgress() {
setState(() {
t.cancel();
donePercentage = 0;
inProgress = false;
done = false;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Row(
children: <Widget>[
Container(
height: widget.height,
width: widget.width / 100 * donePercentage,
color: Colors.green,
child: Center(child: Text("$donePercentage %")),
),
Container(
height: widget.height,
width: widget.width / 100 * (max(0, 100 - donePercentage)),
color: Colors.white,
),
]
)
),
persistentFooterButtons: <Widget>[
FlatButton(
onPressed: _stopProgress,
child: Icon(done ? Icons.restore : Icons.stop),
)
],
floatingActionButton: FloatingActionButton(
onPressed: inProgress ? null : _runProgress,
tooltip: 'Run',
backgroundColor: (inProgress && !done) ? Colors.grey : Colors.green,
child: Icon(done ? Icons.check : Icons.directions_run),
)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment