Created
March 24, 2021 14:20
-
-
Save imaNNeo/6c247f11213f1dc5c6926c399194d8a0 to your computer and use it in GitHub Desktop.
Map custom data for PieChart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:fl_chart/fl_chart.dart'; | |
import 'package:flutter/material.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'FlChart Demo', | |
showPerformanceOverlay: false, | |
theme: ThemeData( | |
primaryColor: const Color(0xff262545), | |
primaryColorDark: const Color(0xff201f39), | |
brightness: Brightness.dark, | |
), | |
home: MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
List<Color> availableColors = [ | |
Colors.red, | |
Colors.green, | |
Colors.blue, | |
Colors.cyan, | |
Colors.greenAccent, | |
Colors.purpleAccent, | |
Colors.deepPurple, | |
]; | |
@override | |
void initState() { | |
super.initState(); | |
} | |
Future<Map<String, int>> getValues() async { | |
await Future.delayed(Duration(seconds: 3)); | |
return {'A': 12, 'B': 32, 'C': 44}; | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
backgroundColor: Colors.white, | |
body: Center( | |
child: Padding( | |
padding: EdgeInsets.all(60), | |
child: FutureBuilder<Map<String, int>>( | |
future: getValues(), | |
builder: (context, snapshot) { | |
if (snapshot.hasData) { | |
Map<String, int> rawData = snapshot.data; | |
List<PieChartSectionData> pieSectionsData = _mapToPieSectionsData(rawData); | |
return PieChart( | |
PieChartData(sections: pieSectionsData), | |
); | |
} else { | |
return CircularProgressIndicator(); | |
} | |
}, | |
), | |
), | |
), | |
); | |
} | |
List<PieChartSectionData> _mapToPieSectionsData(Map<String, int> rawData) { | |
return rawData.entries.map((entry) { | |
String title = entry.key; | |
int value = entry.value; | |
return PieChartSectionData( | |
value: value.toDouble(), | |
title: '$title: $value', | |
color: availableColors[value % availableColors.length], | |
); | |
}).toList(); | |
} | |
} |
Author
imaNNeo
commented
Mar 24, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment