Sunday, June 23, 2024
Google search engine
HomeAnimationExplore Line Chart In Flutter

Explore Line Chart In Flutter

Learn how to create an interactive Line Chart in your Flutter apps

In this article, we will Explore Line Chart In Flutter. We see how to execute a demo program. We will tell you how to create an interactive line chart utilizing the fl_chart package, and how to work it in your Flutter applications.

  • For FL Chart:

fl_chart 0.64.0 | Flutter package
A highly customizable Flutter chart library that supports Line Chart, Bar Chart, Pie Chart, Scatter Chart, and Radar…pub.dev

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

Constructor

Properties

Implementation

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to create an interactive line chart in Flutter and how a line chart will work using the fl_chart plugin in your Flutter applications. We will show you how to create a line chart, and the user presses the line and then shows data on this particular line. It will be shown on your device.

Demo Module::


Constructor:

  • To utilize LineChart, you need to call the constructor underneath:
const LineChart(
this.data, {
this.chartRendererKey,
super.key,
super.duration = const Duration(milliseconds: 150),
super.curve = Curves.linear,
});
  • In LineChart we will use the LineChartData constructor on the data field:
LineChartData({
this.lineBarsData = const [],
this.betweenBarsData = const [],
super.titlesData = const FlTitlesData(),
super.extraLinesData = const ExtraLinesData(),
this.lineTouchData = const LineTouchData(),
this.showingTooltipIndicators = const [],
super.gridData = const FlGridData(),
super.borderData,
super.rangeAnnotations = const RangeAnnotations(),
double? minX,
double? maxX,
super.baselineX,
double? minY,
double? maxY,
super.baselineY,
super.clipData = const FlClipData.none(),
super.backgroundColor,
})

Properties:

There are some properties of LineChartData:

  • > lineBarsData: This property is utilized to draw some lines in various shapes and overlap them.
  • > betweenBarsData: This property is utilized to fill the area between two LineChartBarData with a color or gradient.
  • > lineTouchData: This property is utilized to handle touch behaviors and responses.
  • > showingTooltipIndicators: This property is utilized to show some a popup with information on top of each [LineChartBarData.spots]. Just put line indicator numbers and spot indices you want to show on top of them.
  • > titlesData: This property is utilized to hold data for showing titles on each side of the charts.
  • > gridData: This property is utilized to be responsible for rendering grid lines behind the content of charts, [show] determines showing or hiding all grids.
  • > borderData: This property is utilized to [show] determine to show or hide borders around the chart. [border] Determines the visual look of 4 borders.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
fl_chart: ^0.64.0

Step 2: Import

import 'package:fl_chart/fl_chart.dart';

Step 3: Run flutter packages get in the root directory of your app.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called main.dart inside the lib folder.

In the main .dart file. We will create a new class MyHomePage(). In this class, we will define a list of <int> showingTooltipOnSpots is equal to 21 in the bracket. It shows when the app runs default shows a popup and line on the 21 number. List<int> showingTooltipOnSpots = [21];

Now, we will create a list of FlSpot. It determines the axis based on horizontal and vertical positions.

List<FlSpot> get allSpots => const [
FlSpot(0, 20),
FlSpot(1, 30),
FlSpot(2, 40),
FlSpot(3, 50),
FlSpot(4, 35),
FlSpot(5, 40),
FlSpot(6, 30),
FlSpot(7, 20),
FlSpot(8, 25),
FlSpot(9, 40),
FlSpot(10, 50),
FlSpot(11, 35),
FlSpot(12, 50),
FlSpot(13, 60),
FlSpot(14, 40),
FlSpot(15, 50),
FlSpot(16, 20),
FlSpot(17, 25),
FlSpot(18, 40),
FlSpot(19, 50),
FlSpot(20, 35),
FlSpot(21, 80),
FlSpot(22, 30),
FlSpot(23, 20),
FlSpot(24, 25),
FlSpot(25, 40),
];

Now, we will create lineBarsData is equal to the LineChartBarData() method. In this method, we will add showingIndicators is equal to showingTooltipOnSpots, spots are equal to the allSpots, also add barWidth, gradient, dotData, etc.

final tooltipsOnBar = lineBarsData[0];

final lineBarsData = [
LineChartBarData(
showingIndicators: showingTooltipOnSpots,
spots: allSpots,
isCurved: false,
barWidth: 3,
belowBarData: BarAreaData(
show: true,
gradient: LinearGradient(colors: [
const Color(0xff9DCEFF).withOpacity(0.4),
const Color(0xff92A3FD).withOpacity(0.1),
], begin: Alignment.topCenter, end: Alignment.bottomCenter),
),
dotData: const FlDotData(show: false),
gradient: const LinearGradient(
colors: [Color(0xff9DCEFF), Color(0xff92A3FD)],
),
),
];

In the body, we will add the LineChart() method. Inside this method, we will add the LineChartData() method. In this method, we will add showingTooltipIndicators show showingTooltipOnSpots.map((index) return ShowingTooltipIndicators with LineBarSpot. It shows some pop-up information on top of the line. We will add lineTouchData where enable was true and it is used to handle the touch behavior.

LineChart(
LineChartData(
showingTooltipIndicators:
showingTooltipOnSpots.map((index) {
return ShowingTooltipIndicators([
LineBarSpot(
tooltipsOnBar,
lineBarsData.indexOf(tooltipsOnBar),
tooltipsOnBar.spots[index],
),
]);
}).toList(),
lineTouchData: LineTouchData(
enabled: true,
handleBuiltInTouches: false,
touchCallback: (FlTouchEvent event,
LineTouchResponse? response) {
if (response == null ||
response.lineBarSpots == null) {
return;
}
if (event is FlTapUpEvent) {
final spotIndex =
response.lineBarSpots!.first.spotIndex;
showingTooltipOnSpots.clear();
setState(() {
showingTooltipOnSpots.add(spotIndex);
});
}
},
mouseCursorResolver: (FlTouchEvent event,
LineTouchResponse? response) {
if (response == null ||
response.lineBarSpots == null) {
return SystemMouseCursors.basic;
}
return SystemMouseCursors.click;
},
getTouchedSpotIndicator: (LineChartBarData barData,
List<int> spotIndexes) {
return spotIndexes.map((index) {
return TouchedSpotIndicatorData(
const FlLine(
color: Colors.red,
),
FlDotData(
show: true,
getDotPainter:
(spot, percent, barData, index) =>
FlDotCirclePainter(
radius: 3,
color: Colors.white,
strokeWidth: 3,
strokeColor: const Color(0xffC58BF2),
),
),
);
}).toList();
},
touchTooltipData: LineTouchTooltipData(
tooltipBgColor: const Color(0xffC58BF2),
tooltipRoundedRadius: 20,
getTooltipItems: (List<LineBarSpot> lineBarsSpot) {
return lineBarsSpot.map((lineBarSpot) {
return LineTooltipItem(
"${lineBarSpot.x.toInt()} mins ago",
const TextStyle(
color: Colors.white,
fontSize: 10,
fontWeight: FontWeight.bold,
),
);
}).toList();
},
),
),
lineBarsData: lineBarsData,
minY: 0,
maxY: 110,
titlesData: const FlTitlesData(
show: false,
),
gridData: const FlGridData(show: false),
borderData: FlBorderData(
show: true,
border: Border.all(
color: Colors.transparent,
),
),
),
),

Then, we will add lineBarsData is equal to the variable lineBarsData that we will already create, minY is zero, maxY is 110, titlesData, gridData, and borderData.

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Code File:

import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter_line_chart_data_demo/splash_screen.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const Splash(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<int> showingTooltipOnSpots = [21];

  List<FlSpot> get allSpots => const [
        FlSpot(0, 20),
        FlSpot(1, 30),
        FlSpot(2, 40),
        FlSpot(3, 50),
        FlSpot(4, 35),
        FlSpot(5, 40),
        FlSpot(6, 30),
        FlSpot(7, 20),
        FlSpot(8, 25),
        FlSpot(9, 40),
        FlSpot(10, 50),
        FlSpot(11, 35),
        FlSpot(12, 50),
        FlSpot(13, 60),
        FlSpot(14, 40),
        FlSpot(15, 50),
        FlSpot(16, 20),
        FlSpot(17, 25),
        FlSpot(18, 40),
        FlSpot(19, 50),
        FlSpot(20, 35),
        FlSpot(21, 80),
        FlSpot(22, 30),
        FlSpot(23, 20),
        FlSpot(24, 25),
        FlSpot(25, 40),
      ];

  @override
  Widget build(BuildContext context) {
    final lineBarsData = [
      LineChartBarData(
        showingIndicators: showingTooltipOnSpots,
        spots: allSpots,
        isCurved: false,
        barWidth: 3,
        belowBarData: BarAreaData(
          show: true,
          gradient: LinearGradient(colors: [
            const Color(0xff9DCEFF).withOpacity(0.4),
            const Color(0xff92A3FD).withOpacity(0.1),
          ], begin: Alignment.topCenter, end: Alignment.bottomCenter),
        ),
        dotData: const FlDotData(show: false),
        gradient: const LinearGradient(
          colors: [Color(0xff9DCEFF), Color(0xff92A3FD)],
        ),
      ),
    ];

    final tooltipsOnBar = lineBarsData[0];
    var media = MediaQuery.of(context).size;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
        centerTitle: true,
        automaticallyImplyLeading: false,
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 10),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.circular(25),
              child: Container(
                height: media.width * 0.8,
                width: double.maxFinite,
                decoration: BoxDecoration(
                  color: const Color(0xff9DCEFF).withOpacity(0.3),
                  borderRadius: BorderRadius.circular(25),
                ),
                child: Stack(
                  alignment: Alignment.topLeft,
                  children: [
                    Padding(
                      padding: const EdgeInsets.symmetric(
                          vertical: 20, horizontal: 20),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text(
                            "Heart Rate",
                            style: TextStyle(
                                color: Colors.black,
                                fontSize: 16,
                                fontWeight: FontWeight.w700),
                          ),
                          ShaderMask(
                            blendMode: BlendMode.srcIn,
                            shaderCallback: (bounds) {
                              return const LinearGradient(
                                      colors: [
                                    Color(0xff9DCEFF),
                                    Color(0xff92A3FD)
                                  ],
                                      begin: Alignment.centerLeft,
                                      end: Alignment.centerRight)
                                  .createShader(Rect.fromLTRB(
                                      0, 0, bounds.width, bounds.height));
                            },
                            child: Text(
                              "78 BPM",
                              style: TextStyle(
                                  color: Colors.white.withOpacity(0.7),
                                  fontWeight: FontWeight.w700,
                                  fontSize: 18),
                            ),
                          ),
                        ],
                      ),
                    ),
                    LineChart(
                      LineChartData(
                        showingTooltipIndicators:
                            showingTooltipOnSpots.map((index) {
                          return ShowingTooltipIndicators([
                            LineBarSpot(
                              tooltipsOnBar,
                              lineBarsData.indexOf(tooltipsOnBar),
                              tooltipsOnBar.spots[index],
                            ),
                          ]);
                        }).toList(),
                        lineTouchData: LineTouchData(
                          enabled: true,
                          handleBuiltInTouches: false,
                          touchCallback: (FlTouchEvent event,
                              LineTouchResponse? response) {
                            if (response == null ||
                                response.lineBarSpots == null) {
                              return;
                            }
                            if (event is FlTapUpEvent) {
                              final spotIndex =
                                  response.lineBarSpots!.first.spotIndex;
                              showingTooltipOnSpots.clear();
                              setState(() {
                                showingTooltipOnSpots.add(spotIndex);
                              });
                            }
                          },
                          mouseCursorResolver: (FlTouchEvent event,
                              LineTouchResponse? response) {
                            if (response == null ||
                                response.lineBarSpots == null) {
                              return SystemMouseCursors.basic;
                            }
                            return SystemMouseCursors.click;
                          },
                          getTouchedSpotIndicator: (LineChartBarData barData,
                              List<int> spotIndexes) {
                            return spotIndexes.map((index) {
                              return TouchedSpotIndicatorData(
                                const FlLine(
                                  color: Colors.red,
                                ),
                                FlDotData(
                                  show: true,
                                  getDotPainter:
                                      (spot, percent, barData, index) =>
                                          FlDotCirclePainter(
                                    radius: 3,
                                    color: Colors.white,
                                    strokeWidth: 3,
                                    strokeColor: const Color(0xffC58BF2),
                                  ),
                                ),
                              );
                            }).toList();
                          },
                          touchTooltipData: LineTouchTooltipData(
                            tooltipBgColor: const Color(0xffC58BF2),
                            tooltipRoundedRadius: 20,
                            getTooltipItems: (List<LineBarSpot> lineBarsSpot) {
                              return lineBarsSpot.map((lineBarSpot) {
                                return LineTooltipItem(
                                  "${lineBarSpot.x.toInt()} mins ago",
                                  const TextStyle(
                                    color: Colors.white,
                                    fontSize: 10,
                                    fontWeight: FontWeight.bold,
                                  ),
                                );
                              }).toList();
                            },
                          ),
                        ),
                        lineBarsData: lineBarsData,
                        minY: 0,
                        maxY: 110,
                        titlesData: const FlTitlesData(
                          show: false,
                        ),
                        gridData: const FlGridData(show: false),
                        borderData: FlBorderData(
                          show: true,
                          border: Border.all(
                            color: Colors.transparent,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}



Conclusion:

In the article, I have explained the Line Chart in Flutter; you can modify this code according to your choice. This was a small introduction to the Line Chart in Flutter User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying Line Chart in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on the Line Chart using the fl_chart plugin in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤


If I need to correct something? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

PDF with Flutter

Rest API in Flutter

Charts in Flutter

Spinkit In Flutter

Recent Comments