More
How to Visualize Data in Flutter with fl_chart and Back4App
24 min
introduction data visualization is a crucial aspect of modern applications, helping users understand complex data through intuitive graphs and charts in this tutorial, you will learn how to create interactive and visually appealing charts in your flutter application using the fl chart package additionally, you will integrate back4app—a backend as a service (baas) platform powered by parse server—to store and retrieve data for your charts by the end of this tutorial, you will have a fully functional flutter app that displays dynamic data fetched from back4app using various chart types like line, bar, and pie charts prerequisites to complete this tutorial, you will need a back4app account if you don't have one, you can sign up for a free account at back4app https //www back4app com/ flutter sdk installed on your local machine you can follow the official flutter installation guide https //flutter dev/docs/get started/install for your operating system basic knowledge of dart and flutter if you are new to flutter, consider reviewing the flutter documentation https //flutter dev/docs to familiarize yourself with the basics parse server sdk for flutter added to your project you can learn how to set it up by following the back4app flutter sdk guide https //www back4app com/docs/flutter/parse flutter sdk an ide or text editor such as visual studio code or android studio step 1 – setting up the back4app backend in this step, you will create a new back4app application and set up a data class to store your chart data 1 1 create a new back4app application log in to your back4app dashboard https //dashboard back4app com/ click on "create new app" enter a name for your application, e g , "flutterchartapp" , and click "create" 1 2 set up the data model in your application dashboard, navigate to the "database" section in the left sidebar click on "create a class" at the top of the page in the modal that appears select "custom" enter "salesdata" as the class name click "create class" 1 3 add columns to the class in the "salesdata" class, click on "+" to add a new column add the following columns month type string sales type number your data model is now set up to store monthly sales data, which you will visualize in your flutter app step 2 – populating the database with sample data before fetching data in your app, you need some sample data in your back4app database still in the "salesdata" class, click on "+" to add a new row enter the following sample data repeat the above steps to add all the sample data entries step 3 – setting up the flutter project in this step, you will create a new flutter project and add the necessary dependencies 3 1 create a new flutter project open your terminal and run flutter create flutter chart app navigate to the project directory cd flutter chart app 3 2 add dependencies to pubspec yaml open pubspec yaml and add the following dependencies dependencies flutter sdk flutter fl chart ^0 60 0 parse server sdk flutter ^4 0 1 run flutter pub get to install the packages step 4 – initializing parse in your flutter app to connect your flutter app with back4app, you need to initialize the parse sdk 4 1 obtain back4app application credentials in your back4app dashboard, navigate to "app settings" > "security & keys" note down your application id and client key 4 2 initialize parse in main dart open lib/main dart and modify it as follows import 'package\ flutter/material dart'; import 'package\ parse server sdk flutter/parse server sdk dart'; import 'home page dart'; // you'll create this file in the next step void main() async { widgetsflutterbinding ensureinitialized(); const keyapplicationid = 'your application id'; const keyclientkey = 'your client key'; const keyparseserverurl = 'https //parseapi back4app com'; await parse() initialize( keyapplicationid, keyparseserverurl, clientkey keyclientkey, debug true, ); runapp(myapp()); } class myapp extends statelesswidget { @override widget build(buildcontext context) { return materialapp( title 'flutter chart app', theme themedata( primaryswatch colors blue, ), home homepage(), ); } } replace 'your application id' and 'your client key' with the credentials you obtained from back4app step 5 – fetching data from back4app in this step, you will fetch the sales data from back4app using the parse sdk 5 1 create home page dart create a new file lib/home page dart and add the following code import 'package\ flutter/material dart'; import 'package\ parse server sdk flutter/parse server sdk dart'; import 'package\ fl chart/fl chart dart'; class homepage extends statefulwidget { @override homepagestate createstate() => homepagestate(); } class salesdata { final string month; final double sales; salesdata(this month, this sales); } class homepagestate extends state\<homepage> { list\<salesdata> chartdata = \[]; @override void initstate() { super initstate(); fetchsalesdata(); } future\<void> fetchsalesdata() async { final querybuilder\<parseobject> query = querybuilder\<parseobject>(parseobject('salesdata')); final parseresponse apiresponse = await query query(); if (apiresponse success && apiresponse results != null) { setstate(() { chartdata = apiresponse results! map((data) { final month = data get\<string>('month') ?? ''; final sales = data get\<num>('sales')? todouble() ?? 0 0; return salesdata(month, sales); }) tolist(); }); } else { // handle errors print('error fetching data ${apiresponse error? message}'); } } @override widget build(buildcontext context) { return scaffold( appbar appbar( title text('sales chart'), ), body chartdata isempty ? center(child circularprogressindicator()) padding( padding const edgeinsets all(16 0), child linechart( linechartdata( miny 0, maxy 250, titlesdata fltitlesdata( lefttitles axistitles( sidetitles sidetitles(showtitles true), ), bottomtitles axistitles( sidetitles sidetitles( showtitles true, gettitleswidget bottomtitlewidgets, interval 1, ), ), ), griddata flgriddata(show true), borderdata flborderdata( show true, border border all(color colors grey), ), linebarsdata \[ linechartbardata( spots chartdata asmap() entries map((e) => flspot( e key todouble(), e value sales)) tolist(), iscurved true, barwidth 3, colors \[colors blue], dotdata fldotdata(show true), ), ], ), ), )); } widget bottomtitlewidgets(double value, titlemeta meta) { const style = textstyle( fontsize 12, ); widget text; int index = value toint(); if (index >= 0 && index < chartdata length) { text = text(chartdata\[index] month substring(0, 3), style style); } else { text = text('', style style); } return sidetitlewidget( axisside meta axisside, child text, ); } } explanation salesdata class a simple model class to hold the month and sales data fetchsalesdata() fetches data from the salesdata class in back4app and updates the chartdata list linechart uses fl chart to create a line chart based on the fetched data bottomtitlewidgets() customizes the bottom axis labels to display the month abbreviations step 6 – running the app now that you have set up the frontend and backend, it's time to run your app in your terminal, navigate to your project directory run the app using flutter run you should see a line chart displaying the sales data for each month step 7 – adding interactivity and customization to make your chart more interactive and visually appealing, you can customize it further 7 1 customize chart appearance modify the linechartbardata in your build method linechartbardata( spots chartdata asmap() entries map((e) => flspot( e key todouble(), e value sales)) tolist(), iscurved true, barwidth 3, colors \[colors blue], belowbardata barareadata( show true, colors \[colors blue withopacity(0 3)], ), dotdata fldotdata( show true, ), ) belowbardata adds a filled area below the line dotdata shows dots at each data point 7 2 enable touch interactions you can enable touch interactions to display tooltips add the following to your linechartdata touchdata linetouchdata( touchtooltipdata linetouchtooltipdata( tooltipbgcolor colors blueaccent, ), ), step 8 – displaying different chart types you can also display other types of charts using fl chart 8 1 pie chart example replace the linechart in your build method with a piechart piechart( piechartdata( sections chartdata map((data) { return piechartsectiondata( value data sales, title data month substring(0, 3), color colors primaries\[chartdata indexof(data) % colors primaries length], ); }) tolist(), sectionsspace 2, centerspaceradius 40, ), ) piechartsectiondata defines each section of the pie chart conclusion in this tutorial, you learned how to use the fl chart package to visualize data in your flutter application you integrated back4app as a backend solution to store and retrieve data using the parse sdk by fetching data from back4app and displaying it using various chart types, you can now build dynamic and interactive data visualizations in your flutter apps to further enhance your application, consider exploring other chart types provided by fl chart , such as bar charts and radar charts you can also implement real time data updates by integrating live queries from back4app additional resources back4app documentation https //www back4app com/docs fl chart package on pub dev https //pub dev/packages/fl chart parse sdk for flutter guide https //docs parseplatform org/flutter/guide/ flutter official documentation https //flutter dev/docs please make sure to replace placeholder values like 'your application id' and 'your client key' with your actual back4app credentials happy coding!