Skip to content

Instantly share code, notes, and snippets.

@austinevick
Created July 11, 2023 16:33
Show Gist options
  • Save austinevick/e19654afb527fb1350bf2e00c42e34d1 to your computer and use it in GitHub Desktop.
Save austinevick/e19654afb527fb1350bf2e00c42e34d1 to your computer and use it in GitHub Desktop.
Calculate percentage and progress
class Home extends StatefulWidget {
const Home({super.key});
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: list.length,
itemBuilder: (ctx, i) {
final progress = list[i].score / 100;
final percentage = (list[i].score / 100) * 100;
// Calculate percentage by dividing the actual score by the total value then multiply by 100
return ListTile(
leading: const CircleAvatar(
backgroundColor: Colors.indigo,
child: Icon(
Icons.person,
color: Colors.white,
),
),
title: Text(
"${list[i].name} ${list[i].score.toStringAsFixed(0)} Position"),
trailing: CircleAvatar(
child: Text(
"${percentage.toStringAsFixed(0)}%",
style: const TextStyle(fontSize: 14),
),
),
subtitle: SizedBox(
height: 16,
child: LinearProgressIndicator(
value: progress,
color: getColor(list[i].score),
),
),
);
}));
}
Color getColor(double value) {
if (value <= 5) {
return Colors.green;
} else if (value == 6 || value <= 69) {
return Colors.yellow;
}
return Colors.red;
}
}
List<Scores> list = [
Scores('John', 80),
Scores('Peter', 2),
Scores('Mercy', 8),
Scores('Amina', 50),
];
class Scores {
final String name;
final double score;
Scores(this.name, this.score);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment