Виджет с отслеживанием состояния внутри виджета с отслеживанием состояния: обновление пользовательского интерфейса - PullRequest
0 голосов
/ 06 августа 2020

Добрый вечер!

Я на этом зациклился. У меня есть виджет RevenueBarChart () - с отслеживанием состояния. Этот виджет использует Future Builder для получения данных из API и отображения данных в виде гистограммы. Я пытаюсь поместить эту гистограмму в другой виджет, который также сохраняет состояние. Проблема в том, что диаграмма застревает на счетчике загрузки и фактически не обновляется и не отображается в пользовательском интерфейсе. Данные просто возвращаются из моего API, я просто не знаю, как реализовать код для отображения моей новой диаграммы. Будь то didChangeDepencies, didUpdateWidget или что-то еще. Мой код ниже:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';

import '../providers/companies_provider.dart';
import '../charts/revenue_bar_chart.dart';

class RevenueScreen extends StatefulWidget {
  static const routeName = '/revenue-screen';

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

class _RevenueScreenState extends State<RevenueScreen>
    with AutomaticKeepAliveClientMixin<RevenueScreen> {
  @override
  bool get wantKeepAlive => true;

  Future _historicalData;
  Future _historicalQuarterlyData;

  var _isInit = true;

  @override
  void didChangeDependencies() {
    if (_isInit) {
      final companyTicker = ModalRoute.of(context).settings.arguments as String;
      final loadedCompany = Provider.of<Companies>(context, listen: false)
          .findByTicker(companyTicker);

      _historicalData =
          Companies().getHistoricalData(loadedCompany.tickerSymbol);
      _historicalQuarterlyData =
          Companies().getQuarterlyHistoricalData(loadedCompany.tickerSymbol);
    }
    _isInit = false;
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final companyTicker = ModalRoute.of(context).settings.arguments as String;
    final loadedCompany = Provider.of<Companies>(context, listen: false)
        .findByTicker(companyTicker);
    var truncNumber = NumberFormat.compact();

    return Container(
      color: Colors.black,
      child: ListView(
        children: <Widget>[
          Column(
          children: <Widget>[
            Container(
              height: 250,
                width: double.infinity,
                child: RevenueBarChart(),
            ),
            Container(
              padding: EdgeInsets.only(top: 20),
              height: 50,
              child: Center(
                child: Text(
                  'Yearly Revenue',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
            FutureBuilder(
              future: _historicalData,
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.data == null) {
                  return Container(
                    height: 50,
                    child: Center(
                      child: CircularProgressIndicator(),
                    ),
                  );
                } else {
                  return Container(
                    decoration: BoxDecoration(
                      color: Colors.black,
                      border: Border.all(
                        color: Colors.grey,
                        width: 0.5,
                      ),
                      borderRadius: BorderRadius.circular(10),
                    ),
                    height: 225,
                    width: double.infinity,
                    margin: EdgeInsets.only(left: 60, right: 60),
                    child: ListView.builder(
                      itemCount: snapshot.data.length,
                      itemBuilder: (BuildContext context, int index) {
                        return ListTile(
                          dense: true,
                          leading: Text(
                            snapshot.data[index]['date'].toString(),
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          trailing: Text(
                            truncNumber
                                .format(snapshot.data[index]['revenue'])
                                .toString(),
                            style: TextStyle(
                                color: Colors.white,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        );
                      },
                    ),
                  );
                }
              },
            ),
            SizedBox(
              height: 30,
              width: 1,
            ),
            Container(
              padding: EdgeInsets.only(top: 20),
              height: 50,
              child: Center(
                child: Text(
                  'Quarterly Revenue',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
            FutureBuilder(
              future: _historicalQuarterlyData,
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.data == null) {
                  return Container(
                    height: 50,
                    child: Center(
                      child: CircularProgressIndicator(),
                    ),
                  );
                } else {
                  return Container(
                    decoration: BoxDecoration(
                      color: Colors.black,
                      border: Border.all(
                        color: Colors.grey,
                        width: 0.5,
                      ),
                      borderRadius: BorderRadius.circular(10),
                    ),
                    height: 225,
                    width: double.infinity,
                    margin: EdgeInsets.only(left: 60, right: 60),
                    child: ListView.builder(
                      itemCount: snapshot.data.length,
                      itemBuilder: (BuildContext context, int index) {
                        return ListTile(
                          dense: true,
                          leading: Text(
                            snapshot.data[index]['date'].toString(),
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          trailing: Text(
                            truncNumber
                                .format(snapshot.data[index]['revenue'])
                                .toString(),
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        );
                      },
                    ),
                  );
                }
              },
            ),
            SizedBox(
              height: 50,
              width: 5,
            ),
          ],
        ),
        ],
      ),
    );
  }
}

Заранее спасибо!

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import 'package:stockmarketapp/models/financial_modeling_prep_HD.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

import '../providers/companies_provider.dart';

class RevenueBarChart extends StatefulWidget with ChangeNotifier {
  @override
  _RevenueBarChartState createState() => _RevenueBarChartState();
}

class _RevenueBarChartState extends State<RevenueBarChart> with ChangeNotifier {
  Future<List<IncomeStatementBC>> _revenueDataForChart;
  var _isInit = true;
  bool isFirstLabel;

  @override
  void didChangeDependencies() {
    if (_isInit) {
      final companyTicker = ModalRoute.of(context).settings.arguments as String;
      final loadedCompany = Provider.of<Companies>(context, listen: false)
          .findByTicker(companyTicker);

      _revenueDataForChart =
          Companies().getIncomeStatement(loadedCompany.tickerSymbol);
    }
    _isInit = false;
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    final companyTicker = ModalRoute.of(context).settings.arguments as String;
    final loadedCompany = Provider.of<Companies>(context, listen: false)
        .findByTicker(companyTicker);
    var truncNumber = NumberFormat.compact();
    isFirstLabel = true;

    final List<Color> color = <Color>[];
    color.add(Colors.black12.withOpacity(1));
    color.add(Color.fromRGBO(0, 128, 255, .5));
    color.add(Color.fromRGBO(0, 128, 255, .7));
    color.add(Color.fromRGBO(0, 128, 255, .9));

    final List<double> stops = <double>[];
    stops.add(0);
    stops.add(0.3);
    stops.add(.4);
    stops.add(.6);

    final LinearGradient gradients =
    LinearGradient(
      colors: color,
      stops: stops,
      transform: GradientRotation(
          540.toDouble() * 3.14 / 270
      ),
      begin: Alignment.bottomCenter,
      end: Alignment.topCenter,
    );

    return Container(
      height: 250,
      width: double.infinity,
      child: FutureBuilder<List<IncomeStatementBC>>(
        future: _revenueDataForChart,
        builder: (BuildContext context, AsyncSnapshot<List<IncomeStatementBC>> snapshot) {
          if (snapshot.data != null) {
            return SfCartesianChart(
              onAxisLabelRender: (AxisLabelRenderArgs args) {
                if (args.axisName == 'primaryYAxis' && isFirstLabel) {
                  args.text = ' ';
                  isFirstLabel = false;
                }
              },
              plotAreaBackgroundColor: Colors.black,
              zoomPanBehavior: ZoomPanBehavior(enablePanning: true),
              trackballBehavior: TrackballBehavior(
                  enable: true,
                  activationMode: ActivationMode.singleTap,
                  tooltipSettings: InteractiveTooltip(
                    enable: true,
                    color: Colors.black87,
                    format: 'point.y',
                  )
              ),
              margin: EdgeInsets.only(
                  left: 20,
                  right: 20,
                  top: 10,
                  bottom: 10
              ),
              primaryXAxis: CategoryAxis(
                labelAlignment: LabelAlignment.start,
                maximumLabels: 5,
                labelStyle: TextStyle(color: Colors.white),
                majorGridLines: MajorGridLines(color: Colors.grey, width: 0),
                majorTickLines: MajorTickLines(size: 0),
              ),
              primaryYAxis: NumericAxis(
                  numberFormat: NumberFormat.compact(),
                  opposedPosition: true,
                  tickPosition: TickPosition.inside,
                  maximumLabels: 2,
                  labelStyle: TextStyle(color: Colors.white),
                  labelAlignment: LabelAlignment.start,
                  majorGridLines: MajorGridLines(color: Colors.grey, width: 0),
                  majorTickLines: MajorTickLines(size: 0),
                  minorGridLines: MinorGridLines(color: Colors.grey, width: 0),
                  minorTickLines: MinorTickLines(size: 0)
              ),
              series: <ChartSeries<IncomeStatementBC, String>>[
                ColumnSeries<IncomeStatementBC, String>(
                  gradient: gradients,
                  dataSource: snapshot.data,
                  xValueMapper: (IncomeStatementBC data, _) => data.date,
                  yValueMapper: (IncomeStatementBC data, _) => data.revenue,
                )
              ],
            );
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }
}
...