简体   繁体   English

Flutter:根据父级的变化更新子级状态

[英]Flutter: Update children state from change in parent

NOTE: The code may seem very long, but for this question you don't need to understand every part of it.注意:代码可能看起来很长,但对于这个问题,您不需要了解它的每一部分。

I have an app, which gets data from an API to build a chart with it.我有一个应用程序,它从 API 获取数据以使用它构建图表。 I use the Syncfusion cartesian chart package.我使用 Syncfusion 笛卡尔图表包。 This is an economic indicator, so it brings a date and a value, for example:这是一个经济指标,所以它带来了一个日期和一个值,例如:

[[2015 Oct, 0.24],[2015 Nov, 0.26],[2015 Dec, 0.32],[2016 Jan, 0.35],[2016 Feb, 0.40],[2016 Mar, 0.48]]

So, once the data arrives (It has a loading screen for waiting the data form the HTTP request), I build the chart with it.因此,一旦数据到达(它有一个用于等待来自 HTTP 请求的数据的加载屏幕),我就用它构建图表。

So in this case, my Parent widget is named ChartScreen.所以在这种情况下,我的父小部件被命名为 ChartScreen。 Here's the code:这是代码:

class ChartScreen extends StatefulWidget {

  @override
  State<ChartScreen> createState() => _ChartScreenState();
}

class _ChartScreenState extends State<ChartScreen> {

 String dropdownValue = '';

  initState() {
    dropdownValue = '2016';
    return super.initState();
  }

  @override
  Widget build(BuildContext context) {

    final enterpriseProvider = Provider.of<EnterpriseProvider>(context);
    final resp = enterpriseProvider.indicator;
    List<IpcData> data = _createIpcList(resp, dropdownValue);

    if( data.length == 0 ) {
      return Scaffold(
        appBar: AppBar(
          title: Text('Obteniendo datos...'),
        ),
        body: Container(
          color: Colors.black,
          width: double.infinity,
          height: double.infinity,
          child: Center(
            child: CircularProgressIndicator(),
          ),
        ),
      );
    }

    return 
    Scaffold(
      appBar: AppBar(
        title: Text('IPC'),
        actions:[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: DropdownButton(
              value: dropdownValue,
              icon: const Icon(Icons.arrow_downward),
              iconSize: 24,
              elevation: 16,
              style: const TextStyle(color: Colors.white),
              underline: Container(
                height: 2,
                color: Colors.white,
              ),
              onChanged: (String? newValue) {
                dropdownValue = newValue!;
                data = _createIpcList(resp, dropdownValue);
                setState(() {});
              },
              items: <String>['2016', '2017', '2018', '2019']
                  .map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList()
            ),
          )
        ] 
      ),
      drawer: SideMenu(),
      body: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            child: Container(
              child: ResultChart( formattedData: data )###############################
            ),
          ),
        ],
      )
    );
  }

  _createIpcList(List<List<dynamic>> resp, [String? year]) {

    print('EL AÑOO');
    print(year);

    List<IpcData>finalList = [];

    if(resp.length != 0) {

      for(int i = 0; i < resp.length; i++) {
        
        try {
          resp[i][0] = DateFormat.yMMM().format(DateTime.parse(resp[i][0]));
        } catch(e) {}

      }

    }

    List<IpcData> ipcList = resp.map((e) => IpcData(e[0], e[1])).toList();

    if (year!= null) {
      for(int i = 0; i < ipcList.length; i++){      
        if (ipcList[i].date.contains(year)){
          finalList.add(ipcList[i]);
        }
      }
    }

    return finalList;

  }
} 

With the _createIpcList I format the JSON data, so the chart can use it.我使用 _createIpcList 格式化 JSON 数据,以便图表可以使用它。 I highlighted the line in which I call the child whose state I want to update.我突出显示了我调用要更新其状态的孩子的行。 But before that, you can se that I added a dropdown menu, to select a year from a (hardcoded) list.但在此之前,您可以看到我添加了一个下拉菜单,以从(硬编码)列表中选择一年。 When the dropdown menu selected item changes (see onChanged), I call the SetState and pass the 'year parameter' to the _createIpcList, which filters the data and returns the items that belong to the selected year.当下拉菜单所选项目发生更改时(请参阅 onChanged),我调用 SetState 并将“年份参数”传递给 _createIpcList,后者过滤数据并返回属于所选年份的项目。 Here's the child code:这是子代码:

class ResultChart extends StatefulWidget {

  final List<IpcData> formattedData;

  const ResultChart({
    Key? key, 
    required this.formattedData
  }) : super(key: key);

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

class _ResultChartState extends State<ResultChart> {


  late List<IpcData> _chartData;

  @override
  void initState() {
    _chartData = widget.formattedData;
    super.initState();
  }


  @override
  Widget build(BuildContext context) {

    return Container(
      child: SfCartesianChart(
        backgroundColor: Colors.black,
        enableAxisAnimation: false,
        trackballBehavior: TrackballBehavior(
          enable: true,
          shouldAlwaysShow: true,
          tooltipSettings: InteractiveTooltip(
            borderWidth: 2,
            borderColor: Colors.grey,
            color: Colors.grey[400],
            format: 'point.x : point.y'
          )
        ),
        zoomPanBehavior: ZoomPanBehavior(
          enablePanning: true,
          enablePinching: true,
          enableDoubleTapZooming: true,
          zoomMode: ZoomMode.xy,
        ),
        primaryXAxis: CategoryAxis(
          labelRotation: 90,
          labelStyle: TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.grey[400]
          ),
          axisLine: AxisLine(
            width: 2,
            color: Colors.grey
          ),
          majorGridLines: MajorGridLines(width: 1),
        ),
        primaryYAxis: NumericAxis(
          labelStyle: TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.grey[400]
          ),
          axisLine: AxisLine(
            width: 2,
            color: Colors.grey
          ),
          title: AxisTitle( text: 'IPC', textStyle: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
          majorGridLines: MajorGridLines(width: 1),
        ), 
        series: <ChartSeries>[
        LineSeries<IpcData, String>( 
          color: Colors.blue,
          dataSource: _chartData,
          xValueMapper: (IpcData data, _) => data.date,
          yValueMapper: (IpcData data, _) => data.value
        )
      ],)
    );
  }
}

class IpcData {

  final String date;
  final double value;

  IpcData(this.date, this.value);

}

My problem is that, no matter which year I select, the chart doesn't change.我的问题是,无论我选择哪一年,图表都不会改变。 I know that the 'dropdownValue' changes because I debugged with some prints() but I don´t know how to rebuild or set state of the ResultChart widget.我知道“dropdownValue”会发生变化,因为我调试了一些 prints() 但我不知道如何重建或设置 ResultChart 小部件的状态。

Well it turn out that I continued debugging, and actually the ResultChart Widget was being rebuilt again and again, but I never called the setState fuction inside the children.好吧,结果我继续调试,实际上 ResultChart Widget 正在一次又一次地重建,但我从未在孩子内部调用 setState 函数。 Beginner error I know, but I'm new with Flutter.我知道初学者错误,但我是 Flutter 的新手。 Also sorry for my english, I'm Argentinian也对不起我的英语,我是阿根廷人

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM