Search code examples
flutterdartsetstate

Flutter - How to refresh a Widget on button Click?


I'm making an app where I plot charts of cryptocurrency. I have a file like this, that renders a chart of btc/24h in it. I'm using chart_sparkline package to plot the chart.

I have the following code, and it is not working on a button click, how do I fix this?

import 'package:flutter/material.dart';
import 'package:tracker/renderchart.dart';

class Portfolio extends StatefulWidget {
    @override
    _PortfolioState createState() => _PortfolioState();
}

class _PortfolioState extends State<Portfolio> {
    Widget portfolioChart = RenderPortfolioChart(coin: "bitcoin", days: 1);

    @override
    Widget build(BuildContext context) {
        return Container(
            child: Column(
                children: [
                    portfolioChart,

                    const Padding(padding: EdgeInsets.only(top: 10.0)),

                    const Text("Hello, there!", style: TextStyle(color: Colors.white)),

                    const Padding(padding: EdgeInsets.only(top: 10.0)),

                    ElevatedButton(
                        onPressed: (){
                            print("updating chart");
                            setState(() {
                              portfolioChart = RenderPortfolioChart(coin: "ethereum", days: 1);
                            });
                        },

                        child: Text("ETH"),
                    )
                ]
            ),
        );
    }
}

Basically, the elevatedButton should update the chart, but it is not working in my case, how to fix this?


Solution

  • I fixed this, I was passing constructor parameters of Portfolio to _PortfolioState, this won't update the values the next time. Instead of passing these values to _PortfolioState, I used widget.coin and widget.days to extract the data from the Portfolio class.

    Thanks to this StackOverflow link: Passing Data to a Stateful Widget in Flutter