김은주
김은주

Reputation: 175

How can I show three data in one chart? (flutter/fl_chart)

class BottomChart extends StatefulWidget {
  final List<String> number;

  const BottomChart({this.number});

  @override
  _BottomChartState createState() => _BottomChartState();
}

class _BottomChartState extends State<BottomChart> {
  List<Color> gradientColors = [
    const Color(0xff23b6e6),
    const Color(0xff02d39a),
  ];

  bool showCnfirmed = true;
  bool showRecvred = false;
  bool showDead = false;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        AspectRatio(
          aspectRatio: 1 / 3,
          child: Container(
            child: Padding(
              padding: const EdgeInsets.only(right: 0, left: 34.0, top: 24, bottom: 24),
              child: LineChart(
                if(showCnfirmed){cnfirmedData()}
                if(showRecvred){recvredData()}
                if(showDead){deadData()}
              ),
            ),
          ),
        ),
        SizedBox(
          width: 60,
          height: 34,
          child: Row(
            children: [
              FlatButton(
                onPressed: () {
                  setState(() {
                    showCnfirmed = !showCnfirmed;
                  });
                },
                child: Text(
                  'Confirmed',
                  style: TextStyle(
                    fontSize: 12, color: showCnfirmed ? Colors.white.withOpacity(0.5) :Colors.white)
                  )
              ),
              FlatButton(
                onPressed: () {
                  setState(() {
                    showRecvred = !showRecvred;
                  });
                },
                child: Text(
                  'Recovered',
                  style: TextStyle(
                    fontSize: 12, color: showRecvred ? Colors.white.withOpacity(0.5) :Colors.white)
                  )
              ),
              FlatButton(
                onPressed: () {
                  setState(() {
                    showDead = !showDead;
                  });
                },
                child: Text(
                  'Dead',
                  style: TextStyle(
                    fontSize: 12, color: showDead ? Colors.white.withOpacity(0.5) :Colors.white)
                  )
              ),
            ],
          )
          )
      ],
    );
  }
}

I tired to make a chart that shows three data(actually three lines in a line chart) by whether their button clicked or not, using fl_chart in flutter package.

as you can see the code above, I wrote identifier checking whether button clicked or not and show its data in LineChart() part with if, but it said,

Performing hot reload...
Syncing files to device Android SDK built for x86...
lib/ui/screens/home_page.dart:106:17: Error: Expected an identifier, but got 'if'.
                if(showCnfirmed){cnfirmedData()}
                ^^
lib/ui/screens/home_page.dart:106:17: Error: Expected ')' before this.
                if(showCnfirmed){cnfirmedData()}
                ^^

in the example code, it wrote like this,

LineChart(
                showAvg ? avgData() : mainData(),
              ),

But the example is about two data, and mine is about three data. How can I solve this problem?

Thank you for reading and I'll wait for your advice! :)

Upvotes: 1

Views: 3281

Answers (1)

chunhunghan
chunhunghan

Reputation: 54365

You can copy paste run full code below
You can use Map<int, LineChartData> to do selection
And pass selection[_selected] to LineChart
code snippet

  Map<int, LineChartData> selection;
  int _selected = 0;
  
  @override
  void initState() {
    selection = {0: cnfirmedData(), 1: recvredData(), 2: deadData()};
    super.initState();
  }
  ...  
  child: LineChart(
                  selection[_selected],
                ),  

working demo

enter image description here

full code

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

class BottomChart extends StatefulWidget {
  @override
  _BottomChartState createState() => _BottomChartState();
}

class _BottomChartState extends State<BottomChart> {
  List<Color> gradientColors = [
    const Color(0xff23b6e6),
    const Color(0xff02d39a),
  ];

  Map<int, LineChartData> selection;
  int _selected = 0;
  bool showAvg = false;
  @override
  void initState() {
    selection = {0: cnfirmedData(), 1: recvredData(), 2: deadData()};
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Stack(
        children: <Widget>[
          AspectRatio(
            aspectRatio: 1 / 3,
            child: Container(
              decoration: const BoxDecoration(
                  borderRadius: BorderRadius.all(
                    Radius.circular(18),
                  ),
                  color: Color(0xff232d37)),
              child: Padding(
                padding: const EdgeInsets.only(
                    right: 0, left: 34.0, top: 24, bottom: 24),
                child: LineChart(
                  selection[_selected],
                ),
              ),
            ),
          ),
          SizedBox(
              width: 300,
              height: 34,
              child: Row(
                children: [
                  FlatButton(
                      onPressed: () {
                        setState(() {
                          _selected = 0;
                        });
                      },
                      child: Text('Confirmed',
                          style: TextStyle(
                              fontSize: 12,
                              color: _selected == 0
                                  ? Colors.white.withOpacity(0.5)
                                  : Colors.white))),
                  FlatButton(
                      onPressed: () {
                        setState(() {
                          _selected = 1;
                        });
                      },
                      child: Text('Recovered',
                          style: TextStyle(
                              fontSize: 12,
                              color: _selected == 1
                                  ? Colors.white.withOpacity(0.5)
                                  : Colors.white))),
                  FlatButton(
                      onPressed: () {
                        print("dead");
                        setState(() {
                          _selected = 2;
                        });
                      },
                      child: Text('Dead',
                          style: TextStyle(
                              fontSize: 12,
                              color: _selected == 2
                                  ? Colors.white.withOpacity(0.5)
                                  : Colors.white))),
                ],
              ))
        ],
      ),
    );
  }

  LineChartData cnfirmedData() {
    return LineChartData(
      gridData: FlGridData(
        show: true,
        drawVerticalLine: true,
        getDrawingHorizontalLine: (value) {
          return FlLine(
            color: const Color(0xff37434d),
            strokeWidth: 1,
          );
        },
        getDrawingVerticalLine: (value) {
          return FlLine(
            color: const Color(0xff37434d),
            strokeWidth: 1,
          );
        },
      ),
      titlesData: FlTitlesData(
        show: true,
        bottomTitles: SideTitles(
          showTitles: true,
          reservedSize: 22,
          getTextStyles: (value) => const TextStyle(
              color: Color(0xff68737d),
              fontWeight: FontWeight.bold,
              fontSize: 16),
          getTitles: (value) {
            switch (value.toInt()) {
              case 2:
                return 'MAR';
              case 5:
                return 'JUN';
              case 8:
                return 'SEP';
            }
            return '';
          },
          margin: 8,
        ),
        leftTitles: SideTitles(
          showTitles: true,
          getTextStyles: (value) => const TextStyle(
            color: Color(0xff67727d),
            fontWeight: FontWeight.bold,
            fontSize: 15,
          ),
          getTitles: (value) {
            switch (value.toInt()) {
              case 1:
                return '10k';
              case 3:
                return '30k';
              case 5:
                return '50k';
            }
            return '';
          },
          reservedSize: 28,
          margin: 12,
        ),
      ),
      borderData: FlBorderData(
          show: true,
          border: Border.all(color: const Color(0xff37434d), width: 1)),
      minX: 0,
      maxX: 11,
      minY: 0,
      maxY: 6,
      lineBarsData: [
        LineChartBarData(
          spots: [
            FlSpot(0, 1),
            FlSpot(2.6, 2),
            FlSpot(4.9, 3),
            FlSpot(6.8, 4.1),
            FlSpot(8, 1),
            FlSpot(9.5, 3),
            FlSpot(11, 4),
          ],
          isCurved: true,
          colors: gradientColors,
          barWidth: 5,
          isStrokeCapRound: true,
          dotData: FlDotData(
            show: false,
          ),
          belowBarData: BarAreaData(
            show: true,
            colors:
                gradientColors.map((color) => color.withOpacity(0.3)).toList(),
          ),
        ),
      ],
    );
  }

  LineChartData recvredData() {
    return LineChartData(
      lineTouchData: LineTouchData(enabled: false),
      gridData: FlGridData(
        show: true,
        drawHorizontalLine: true,
        getDrawingVerticalLine: (value) {
          return FlLine(
            color: const Color(0xff37434d),
            strokeWidth: 1,
          );
        },
        getDrawingHorizontalLine: (value) {
          return FlLine(
            color: const Color(0xff37434d),
            strokeWidth: 1,
          );
        },
      ),
      titlesData: FlTitlesData(
        show: true,
        bottomTitles: SideTitles(
          showTitles: true,
          reservedSize: 22,
          getTextStyles: (value) => const TextStyle(
              color: Color(0xff68737d),
              fontWeight: FontWeight.bold,
              fontSize: 16),
          getTitles: (value) {
            switch (value.toInt()) {
              case 2:
                return 'MAR';
              case 5:
                return 'JUN';
              case 8:
                return 'SEP';
            }
            return '';
          },
          margin: 8,
        ),
        leftTitles: SideTitles(
          showTitles: true,
          getTextStyles: (value) => const TextStyle(
            color: Color(0xff67727d),
            fontWeight: FontWeight.bold,
            fontSize: 15,
          ),
          getTitles: (value) {
            switch (value.toInt()) {
              case 1:
                return '10k';
              case 3:
                return '30k';
              case 5:
                return '50k';
            }
            return '';
          },
          reservedSize: 28,
          margin: 12,
        ),
      ),
      borderData: FlBorderData(
          show: true,
          border: Border.all(color: const Color(0xff37434d), width: 1)),
      minX: 0,
      maxX: 11,
      minY: 0,
      maxY: 6,
      lineBarsData: [
        LineChartBarData(
          spots: [
            FlSpot(0, 3.44),
            FlSpot(2.6, 3.44),
            FlSpot(4.9, 3.44),
            FlSpot(6.8, 3.44),
            FlSpot(8, 3.44),
            FlSpot(9.5, 3.44),
            FlSpot(11, 3.44),
          ],
          isCurved: true,
          colors: [
            ColorTween(begin: gradientColors[0], end: gradientColors[1])
                .lerp(0.2),
            ColorTween(begin: gradientColors[0], end: gradientColors[1])
                .lerp(0.2),
          ],
          barWidth: 5,
          isStrokeCapRound: true,
          dotData: FlDotData(
            show: false,
          ),
          belowBarData: BarAreaData(show: true, colors: [
            ColorTween(begin: gradientColors[0], end: gradientColors[1])
                .lerp(0.2)
                .withOpacity(0.1),
            ColorTween(begin: gradientColors[0], end: gradientColors[1])
                .lerp(0.2)
                .withOpacity(0.1),
          ]),
        ),
      ],
    );
  }

  LineChartData deadData() {
    return LineChartData(
      gridData: FlGridData(
        show: true,
        drawVerticalLine: true,
        getDrawingHorizontalLine: (value) {
          return FlLine(
            color: const Color(0xff37434d),
            strokeWidth: 1,
          );
        },
        getDrawingVerticalLine: (value) {
          return FlLine(
            color: const Color(0xff37434d),
            strokeWidth: 1,
          );
        },
      ),
      titlesData: FlTitlesData(
        show: true,
        bottomTitles: SideTitles(
          showTitles: true,
          reservedSize: 22,
          getTextStyles: (value) => const TextStyle(
              color: Color(0xff68737d),
              fontWeight: FontWeight.bold,
              fontSize: 16),
          getTitles: (value) {
            switch (value.toInt()) {
              case 2:
                return 'MAR';
              case 5:
                return 'JUN';
              case 8:
                return 'SEP';
            }
            return '';
          },
          margin: 8,
        ),
        leftTitles: SideTitles(
          showTitles: true,
          getTextStyles: (value) => const TextStyle(
            color: Color(0xff67727d),
            fontWeight: FontWeight.bold,
            fontSize: 15,
          ),
          getTitles: (value) {
            switch (value.toInt()) {
              case 1:
                return '10k';
              case 3:
                return '30k';
              case 5:
                return '50k';
            }
            return '';
          },
          reservedSize: 28,
          margin: 12,
        ),
      ),
      borderData: FlBorderData(
          show: true,
          border: Border.all(color: const Color(0xff37434d), width: 1)),
      minX: 0,
      maxX: 11,
      minY: 0,
      maxY: 6,
      lineBarsData: [
        LineChartBarData(
          spots: [
            FlSpot(0, 3),
            FlSpot(2.6, 2),
            FlSpot(4.9, 5),
            FlSpot(6.8, 3.1),
            FlSpot(8, 4),
            FlSpot(9.5, 3),
            FlSpot(11, 4),
          ],
          isCurved: true,
          colors: gradientColors,
          barWidth: 5,
          isStrokeCapRound: true,
          dotData: FlDotData(
            show: false,
          ),
          belowBarData: BarAreaData(
            show: true,
            colors:
                gradientColors.map((color) => color.withOpacity(0.3)).toList(),
          ),
        ),
      ],
    );
  }
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: BottomChart(),
    );
  }
}

Upvotes: 2

Related Questions