Visualize Election Results Using the Flutter Treemap Widget
Tags: flutter, dart, mobile, webdev
Published: 2021-07-29 12:39:12

---
title: Visualize Election Results Using the Flutter Treemap Widget
published: true
date: 2021-07-29 11:30:05 UTC
tags: flutter, dart, mobile, webdev
canonical_url: https://www.syncfusion.com/blogs/post/visualize-election-results-using-the-flutter-treemap-widget.aspx
cover_image: https://www.syncfusion.com/blogs/wp-content/uploads/2021/07/Visualize-Election-Results-Using-the-Flutter-Treemap-Widget-672x372.png
---

The Syncfusion [Flutter Treemap](https://www.syncfusion.com/flutter-widgets/flutter-treemap "Link to Flutter Treemap") is a data visualization widget. It visualizes flat and hierarchical data as tiles (rectangles) that are sized and colored based on the quantitative values. Its features include data binding, legends, data labels, tooltips, color mapping, layout types, drill-down, and more. This blog post explores the step-by-step process of how to visualize election results using the Flutter Treemap widget.

We are going to render a treemap representing the presidential election of the United States with tiles, legends, a tooltip, and two different colors to represent the candidates. The following GIF image depicts the Treemap we will build in this blog.

![Visualizing Election Results Using Flutter Treemap](https://www.syncfusion.com/blogs/wp-content/uploads/2021/07/Visualizing-Election-Results-Using-Flutter-Treemap-1.gif)<figcaption>Visualizing Election Results Using Flutter Treemap</figcaption>

**Note:** The Treemap information is sourced from the [2020 United States presidential election](https://en.wikipedia.org/wiki/2020_United_States_presidential_election "Link to 2020 United States presidential election Wikipedia page").

In the above GIF image, the tile size is calculated based on the population (voter count) of the state, and the color is applied based on the winner of that state. The tooltip displays the candidate’s name, state, and vote percentage details.

## Installation and configuration

Follow these steps to install and configure the Flutter Treemap widget in your application:

1. First, create a simple project using the instructions given in the [Getting Started with your first Flutter app](https://flutter.dev/docs/get-started/test-drive?tab=vscode#create-app "Link to Getting Started with your first Flutter app documentation") documentation.
2. Then, add the Syncfusion Flutter Treemap dependency to your pubspec.yaml file with the current version of the [Syncfusion Flutter Treemap](https://pub.dev/packages/syncfusion_flutter_treemap/versions "Link to Syncfusion Flutter Treemap package on pub.dev") package.  
Refer to the following code.

| `dependencies:
syncfusion_flutter_treemap: ^xx.x.xx
` |

1. Now, import the library using the following code.  

| `import 'package:syncfusion_flutter_treemap/treemap.dart';` |

## Populate data source and initialize the Treemap

Follow these steps to populate the election results in the Flutter Treemap:

1. We are going to display the results for each state in the U.S.A. Thus, the Treemap should have a tile (rectangle) for each state. So, we have to set the number of states in the U.S.A as the value for the [dataCount ](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/dataCount.html "Link to the dataCount property of Flutter TreeMap")property.
2. The next thing the Treemap needs to know is the size of each tile. In an election result, the tile size represents the population (voters) of each state. So, we have to return the voters count in each state from the [weightValueMapper](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/weightValueMapper.html "Link to weightValueMapper property of Flutter TreeMap") callback of the Treemap.
3. Now, group the election results in order of the state in the Flutter Treemap. Return the state name from the [groupMapper](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/groupMapper.html "Link to groupMapper property of Flutter TreeMap") callback. You can have more than one [TreemapLevel](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel-class.html "Link to TreemapLevel class in Flutter TreeMap") in the [levels](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/levels.html "Link to levels property of Flutter TreeMap") collection to form a hierarchical Treemap. As this election result is a flat structure, we have only one [TreemapLevel](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel-class.html "Link to TreemapLevel class in Flutter TreeMap").Refer to the following code snippet. Here, we have taken the details of only five states from the data source to provide better readability.
```dart
late List<_StateElectionDetails> _stateWiseElectionResult;

  @override
  void initState() {
    // Define the data source.
    _stateWiseElectionResult = <_StateElectionDetails>[
      const _StateElectionDetails(
          state: 'Washington',
          candidate: 'Joe Biden',
          party: 'Democratic',
          totalVoters: 4087631,
          votes: 2369612,
          percentage: 57.97),
      const _StateElectionDetails(
          state: 'Oregon',
          candidate: 'Joe Biden',
          party: 'Democratic',
          totalVoters: 2374321,
          votes: 1340383,
          percentage: 56.45),
      const _StateElectionDetails(
          state: 'Alabama',
          candidate: 'Donald Trump',
          party: 'Republican',
          totalVoters: 2323282,
          votes: 1441170,
          percentage: 62.03),
      const _StateElectionDetails(
          state: 'Arizona',
          candidate: 'Joe Biden',
          party: 'Democratic',
          totalVoters: 3387326,
          votes: 1672143,
          percentage: 49.36),
      const _StateElectionDetails(
          state: 'Arkansas',
          candidate: 'Donald Trump',
          party: 'Republican',
          totalVoters: 1219069,
          votes: 760647,
          percentage: 62.40),
    ];

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: SfTreemap(
        // Set the data source length.
        dataCount: _stateWiseElectionResult.length,
        // Return the population of the state
        weightValueMapper: (int index) {
          return _stateWiseElectionResult[index].totalVoters;
        },
        levels: [
          TreemapLevel(
            // Update the group mapper
            groupMapper: (int index) => _stateWiseElectionResult[index].state,
          ),
        ],
      ),
    );
  }
```

After executing this code, we will get output like in the following screenshot.

![Rendering a Simple Flutter Treemap](https://www.syncfusion.com/blogs/wp-content/uploads/2021/07/Rendering-a-Simple-Flutter-Treemap-1.png)<figcaption>Rendering a Simple Flutter Treemap</figcaption>

## Enable the labels to identify the states in tiles

In the previous Treemap, it is unclear that which tile belongs to which state. The rescue comes through the labels feature, through which we are going to put the state names in the tiles. To do so, return the text widget from the [labelBuilder](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/labelBuilder.html "Link to labelBuilder property of Flutter TreeMap") callback.

Refer to the following code example.

```dart
@override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: SfTreemap(
        dataCount: _stateWiseElectionResult.length,
        weightValueMapper: (int index) {
          return _stateWiseElectionResult[index].totalVoters;
        },
        levels: [
          TreemapLevel(
            groupMapper: (int index) => _stateWiseElectionResult[index].state,
            
            // Write the state name in each tile.
            labelBuilder: (BuildContext context, TreemapTile tile) {
              return Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  tile.group,
                  style: TextStyle(color: Colors.white),
                ),
              );
            },
          ),
        ],
      ),
    );
  }
```

After executing this code, we will get the output like in the following screenshot.

![Enabling Labels in Flutter Treemap](https://www.syncfusion.com/blogs/wp-content/uploads/2021/07/Enabling-Labels-in-Flutter-Treemap.png)<figcaption>Enabling Labels in Flutter Treemap</figcaption>

## Update the tile color based on the winning party

So, everything works as expected. Next, we are going to change the tile color based on the winning candidate in that state (tile). To do this, update the [TreemapColorMapper](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapColorMapper-class.html "Link to TreemapColorMapper class in Flutter TreeMap") collection to the Treemap’s [colorMappers](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/colorMappers.html "Link to colorMappers property of Flutter TreeMap") property. Then, update the Treemaplevel’s [colorValueMapper](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/colorValueMapper.html "Link to colorValueMapper property of Flutter TreeMap") property.

Refer to the following code example.

```dart
late List _colorMappers;

@override
  void initState() {

    //Update the data from previous code example for data source.
    _stateWiseElectionResult = <_StateElectionDetails>[];

    //Define the color values for both parties.
    _colorMappers = [
      const TreemapColorMapper.value(value: 'Democratic', color: Colors.blue),
      const TreemapColorMapper.value(
          value: 'Republican', color: Colors.orangeAccent),
    ];

    super.initState();
}

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: SfTreemap(
        dataCount: _stateWiseElectionResult.length,
        weightValueMapper: (int index) {
          return _stateWiseElectionResult[index].totalVoters;
        },
        colorMappers: _colorMappers,
        levels: [
          TreemapLevel(
            groupMapper: (int index) => _stateWiseElectionResult[index].state,
            labelBuilder: (BuildContext context, TreemapTile tile) {
              return Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  tile.group,
                  style: TextStyle(color: Colors.white),
                ),
              );
            },

            //Update the title color to represent the winning party.
            colorValueMapper: (TreemapTile tile) {
              return _stateWiseElectionResult[tile.indices[0]].party;
            },
          ),
        ],
      ),
    );
  }
```

After executing this code, we will get output like in the following screenshot.

![Applying Colors to the Tiles Based on the Winning Party Details](https://www.syncfusion.com/blogs/wp-content/uploads/2021/07/Applying-Colors-to-the-Tiles-Based-on-the-Winning-Party-Details-1.png)<figcaption>Applying Colors to the Tiles Based on the Winning Party Details</figcaption>

## Adding a legend to the Treemap

By default, the legend items’ text is rendered based on the value of the [TreemapLevel.groupMapper](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/groupMapper.html "Link to the groupMapper property of Flutter TreeMap") property, which we have already defined. So, just setting the position and size of the legend is enough.

Refer to the following code example to add a legend to identify the parties based on color.

```dart
@override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: SfTreemap(
        dataCount: _stateWiseElectionResult.length,
        weightValueMapper: (int index) {
          return _stateWiseElectionResult[index].totalVoters;
        },
        colorMappers: _colorMappers,
        levels: [
          TreemapLevel(
            groupMapper: (int index) => _stateWiseElectionResult[index].state,
            labelBuilder: (BuildContext context, TreemapTile tile) {
              return Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  tile.group,
                  style: TextStyle(color: Colors.white),
                ),
              );
            },
            colorValueMapper: (TreemapTile tile) {
              return _stateWiseElectionResult[tile.indices[0]].party;
            },
          ),
        ],

        // Enable the legend
        legend: TreemapLegend.bar(
          position: TreemapLegendPosition.bottom,
          segmentSize: const Size(80.0, 12.0),
        ),
      ),
    );
  }
```

After executing this code, we will get output like in the following screenshot.

![Adding Legends to the Flutter Treemap](https://www.syncfusion.com/blogs/wp-content/uploads/2021/07/Adding-Legends-to-the-Flutter-Treemap-1.png)<figcaption>Adding Legends to the Flutter Treemap</figcaption>

## Enable the tooltip

You can enable the tooltips to display additional information about the tiles when the pointer hovers over them or on tap events. For this, return a widget in the [TreemapLevel.tooltipBuilder](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/tooltipBuilder.html "Link to tooltipBuilder property of Flutter TreeMap") method. This widget will then be wrapped in the built-in shape that comes with the pointer at the bottom.

Refer to the following code.

```dart
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: SfTreemap(
        dataCount: _stateWiseElectionResult.length,
        weightValueMapper: (int index) {
          return _stateWiseElectionResult[index].totalVoters;
        },
        colorMappers: _colorMappers,
        levels: [
          TreemapLevel(
              groupMapper: (int index) => _stateWiseElectionResult[index].state,
              labelBuilder: (BuildContext context, TreemapTile tile) {
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                    tile.group,
                    style: TextStyle(color: Colors.white),
                  ),
                );
              },

              colorValueMapper: (TreemapTile tile) {
                return _stateWiseElectionResult[tile.indices[0]].party;
              },

              // Enable the tooltip.
              tooltipBuilder: (BuildContext context, TreemapTile tile) {
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: RichText(
                      text: TextSpan(
                          text: _stateWiseElectionResult[tile.indices[0]]
                              .candidate,
                          children: [
                        TextSpan(
                              text: '\n${tile.group}',
                            ),

                        TextSpan(
                          text: '\nWon percentage : ' +
                              _stateWiseElectionResult[tile.indices[0]]
                                  .percentage
                                  .toString() +
                              '%',
                        ),
                      ])),
                );
              }),
        ],

        legend: TreemapLegend.bar(
          position: TreemapLegendPosition.bottom,
          segmentSize: const Size(80.0, 12.0),
        ),
      ),
    );
  }
```

After executing this code, we will get the output like in the following screenshot.

![Enabling Tooltips in Flutter Treemap](https://www.syncfusion.com/blogs/wp-content/uploads/2021/07/Enabling-Tooltips-in-Flutter-Treemap-1.png)<figcaption>Enabling Tooltips in Flutter Treemap</figcaption>

## Resource

For more information, refer to the [Visualize Election Results with Flutter Treemap demo](https://github.com/SyncfusionExamples/visualize_election_results_with_treemap "Link to Visualize Election Results with Flutter Treemap demo on GitHub").

## Conclusion

Thanks for reading! In this blog, we have seen how to visualize election results using the Syncfusion [Flutter Treemap](https://www.syncfusion.com/flutter-widgets/flutter-treemap "Link to Flutter Treemap") widget. With this widget, you can also visualize literacy rates, weather reports, and more with the versatile and colorful features in it. To learn more, you can also check out our Flutter Treemap widget’s [user guide](https://help.syncfusion.com/flutter/treemap/overview "Link to Flutter Treemap (SfTreemap) Overview") and [example projects](https://github.com/syncfusion/flutter-examples "Link to the Syncfusion Flutter examples on GitHub"). Try out the steps given in this blog post and leave your feedback in the comments section of this blog post!

Don’t miss our demo app in [Google Play](https://play.google.com/store/apps/details?id=com.syncfusion.flutter.examples&hl=en "Link to Flutter Treemap demos on Google Play Store"), the [App Store](https://apps.apple.com/in/app/syncfusion-flutter-ui-widgets/id1475231341 "Link to Flutter Treemap demos on the App Store"), the [Windows Store](https://www.microsoft.com/en-us/p/syncfusion-flutter-gallery/9nhnbwcsf85d?activetab=pivot:overviewtab "Link to Flutter Treemap demos on the Windows Store"), the [App Center](https://install.appcenter.ms/orgs/syncfusion-demos/apps/syncfusion-flutter-gallery/distribution_groups/release "Link to Flutter Treemap demos on the App Center"), [Snapcraft,](https://snapcraft.io/syncfusion-flutter-gallery "Link to Flutter Treemap demos on Snapcraft") and on our [website](https://flutter.syncfusion.com/ "Link to Flutter Treemap demos on web").

You can contact us through our [support forum](https://www.syncfusion.com/forums "Link to the Syncfusion support forum"), [Direct-Trac](https://www.syncfusion.com/support/directtrac/incidents "Link to the Syncfusion support system Direct Trac"), or [feedback portal](https://www.syncfusion.com/feedback/flutter "Link to Syncfusion Feedback Portal"). As always, we are happy to assist you!

## Related blogs

- [Introducing the New Flutter Treemap Widget](https://dev.to/sureshmohan/introducing-the-new-flutter-treemap-widget-j44-temp-slug-6496028 "Link to the Introducing the New Flutter Treemap Widget blog")
- [Introducing Editing Functionality in Flutter DataGrid](https://dev.to/sureshmohan/introducing-editing-functionality-in-flutter-datagrid-59hc-temp-slug-9192836 "Link to the Introducing Editing Functionality in Flutter DataGrid blog")
- [How to Create a Balance Sheet Using Flutter Excel Library](https://dev.to/syncfusion/how-to-create-a-balance-sheet-using-flutter-excel-library-4g7o "Link to the How to Create a Balance Sheet Using Flutter Excel Library blog")
- [Easy Ways to Build a Heat Map Calendar Using the Flutter Event Calendar](https://dev.to/syncfusion/easy-ways-to-build-a-heat-map-calendar-using-the-flutter-event-calendar-36bn "Link to the Easy Ways to Build a Heat Map Calendar Using the Flutter Event Calendar blog")