imaNNeo / imaNNeo/fl_chart

Tooltop shows behind of others widget

Open
#1,766 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Dart
Stars
7.6k
Forks
2k
Avg merge
9d 1h
Merged PRs (30d)
2

Description

image

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

import '../../../../../shared/utils/extensions/number.extension.dart';
import '../../../models/transacao_model.dart';

class GraficoGastosSemanais extends StatefulWidget {
  final List<Transacao> transacoes;
  final double meta;
  final String metaTitle;

  GraficoGastosSemanais({required this.transacoes, required this.meta, required this.metaTitle});

  @override
  State<GraficoGastosSemanais> createState() => _GraficoGastosSemanaisState();
}

class _GraficoGastosSemanaisState extends State<GraficoGastosSemanais> {
  int? touchedIndex;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final saldoSemanal = calcularSaldoSemanal(widget.transacoes);

    // Calcula o maior e menor valor do saldo semanal para ajustar a escala
    final double maxValor = saldoSemanal.values.map((entry) => entry['total']!).reduce((a, b) => a > b ? a : b);
    final double minValor = saldoSemanal.values.map((entry) => entry['total']!).reduce((a, b) => a < b ? a : b);

    return BarChart(
      BarChartData(
        alignment: BarChartAlignment.spaceAround,
        barGroups: saldoSemanal.entries.map((entry) {
          final index = saldoSemanal.keys.toList().indexOf(entry.key);
          return BarChartGroupData(
            x: index,
            groupVertically: true,
            barRods: [
              // Barra de Ganhos
              BarChartRodData(
                toY: entry.value['total']!,
                color: Color(0xffA8D9A0),
                width: 16,
                borderRadius: BorderRadius.vertical(top: Radius.circular(4)),
              ),
              // Barra de Gastos
              BarChartRodData(
                toY: -entry.value['saida']!, // Negativo para gastos
                color: Color(0xffFD9DCD),
                width: 16,
                borderRadius: BorderRadius.vertical(bottom: Radius.circular(4)),
              ),
            ],
            showingTooltipIndicators: touchedIndex == index ? [0, 1] : [], // Mostra tooltip se a barra foi clicada
          );
        }).toList(),
        titlesData: FlTitlesData(
          topTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
          leftTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
          rightTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 40,
              getTitlesWidget: (value, meta) {
                if (value == meta.max || value == meta.min) {
                  return Container();
                }

                return Text(value.toString(), style: TextStyle(fontSize: 12));
              },
            ),
          ),
          bottomTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              getTitlesWidget: (value, _) {
                const dias = ['Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab', 'Dom'];
                return Text(
                  dias[value.toInt()],
                  style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold),
                );
              },
            ),
          ),
        ),
        barTouchData: BarTouchData(
          touchCallback: (event, response) {
            if (response != null && response.spot != null && event is FlTapUpEvent) {
              setState(() {
                final x = response.spot!.touchedBarGroup.x;
                final isShowing = touchedIndex == x;
                if (isShowing) {
                  touchedIndex = -1;
                } else {
                  touchedIndex = x;
                }
              });
            }
          },
          touchTooltipData: BarTouchTooltipData(
            getTooltipColor: (group) => Colors.grey.shade200,
            getTooltipItem: (group, groupIndex, rod, rodIndex) {
              final valor = rod.toY;

              // Exibe apenas se o valor for maior que 0
              if (valor != 0) {
                return BarTooltipItem(
                  'R\$ ${valor.format()}',
                  TextStyle(color: Colors.black, fontSize: 12),
                );
              } else {
                return null; // Não exibe tooltip se valor <= 0
              }
            },
          ),
        ),
        gridData: FlGridData(show: false),
        borderData: FlBorderData(show: false),
        minY: minValor - 100, // Ajuste para deixar o gráfico mais claro visualmente
        maxY: widget.meta > maxValor ? widget.meta + 100 : maxValor + 100,
        extraLinesData: ExtraLinesData(
          horizontalLines: [
            HorizontalLine(
              y: widget.meta,
              color: Colors.blue,
              strokeWidth: 2,
              dashArray: [5, 5],
              label: HorizontalLineLabel(
                show: true,
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.only(bottom: 32),
                labelResolver: (_) => '${widget.metaTitle} \nR\$ ${widget.meta.format()}',
              ),
            ),
            HorizontalLine(
              y: 0,
              color: Colors.grey,
              strokeWidth: 1,
              dashArray: [5, 5],
            ),
          ],
        ),
      ),
    );
  }

  Map<String, Map<String, double>> calcularSaldoSemanal(List<Transacao> transacoes) {
    final Map<String, Map<String, double>> saldoPorDia = {
      'Seg': {'entrada': 0.0, 'saida': 0.0},
      'Ter': {'entrada': 0.0, 'saida': 0.0},
      'Qua': {'entrada': 0.0, 'saida': 0.0},
      'Qui': {'entrada': 0.0, 'saida': 0.0},
      'Sex': {'entrada': 0.0, 'saida': 0.0},
      'Sab': {'entrada': 0.0, 'saida': 0.0},
      'Dom': {'entrada': 0.0, 'saida': 0.0},
    };

    for (var transacao in transacoes) {
      String dia = obterNomeDoDia(transacao.dataHora);
      if (transacao.tipo == EnumTipoTransacao.entrada) {
        saldoPorDia[dia]!['entrada'] = (saldoPorDia[dia]!['entrada'] ?? 0) + transacao.valor;
      } else {
        saldoPorDia[dia]!['saida'] = (saldoPorDia[dia]!['saida'] ?? 0) + transacao.valor;
      }
    }

    // Calcular o total para cada dia
    saldoPorDia.forEach((key, value) {
      value['total'] = value['entrada']! - value['saida']!;
    });

    return saldoPorDia;
  }

  String obterNomeDoDia(DateTime data) {
    switch (data.weekday) {
      case 1:
        return 'Seg';
      case 2:
        return 'Ter';
      case 3:
        return 'Qua';
      case 4:
        return 'Qui';
      case 5:
        return 'Sex';
      case 6:
        return 'Sab';
      case 7:
        return 'Dom';
      default:
        return '';
    }
  }
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the GraficoGastosSemanais example in the issue, especially BarTouchData and BarTouchTooltipData, and reproduce the tooltip layering problem with overlapping widgets. Trace how the chart renders its tooltip and compare the result with the attached image. Done means the tooltip appears in front of the other widget instead of behind it.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart, flutter
Domain
frontend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.