Передача данных из родительского в дерево виджетов во флаттере - PullRequest
0 голосов
/ 21 апреля 2020

У меня есть виджет моего дерева, подобный этому enter image description here

На самом деле, я передаю данные в виджете конструктора из history_screen в history_item и из history_item в line_graph, и получаю некоторые проблемы:

Мой streamBuilder в history_screen это:

child: StreamBuilder(
  stream: dbRef.child('info_tekax/demo').limitToLast(10).onValue,
  builder: (context, snapshot) {
    if(snapshot.hasData && !snapshot.hasError){
      Map data = snapshot.data.snapshot.value;
      List keys = [];
      data.forEach( (index, data) => keys.add(index) );

      return ListView.builder(
        itemCount: data.length,
        itemBuilder: (context, index) {
          if(keys[index] != 'configs' && keys[index] != 'sensores')
            return HistoryItem(data: data, index: index, nameKey: keys[index],  bottom: 10);
          else
            return SizedBox(height: 0);
        } 
      );
    }else{
      return Container(
        child: Center(
          child: CircularProgressIndicator(),
        ),
      );
    }
  }
),

Я хочу передать виджет моих детей (history_item), только дети нарисованы, как вы видите, на самом деле я передаю все данные получить из StreamBuilder return HistoryItem(data: data, ...); i wi sh передать только элемент, например return HistoryItem(data: data[index], ...);

Проблема в том, что когда я делаю так, в моем виджете детей я всегда получаю ноль.

С другой стороны, это мой history_item

class HistoryItem extends StatefulWidget {
  Map data;
  int index;
  String nameKey;
  double bottom = 10;
  String title = '';

  HistoryItem({ Key key, @required this.data, @required this.index, @required this.nameKey, @required this.bottom });

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

class _HistoryItemState extends State<HistoryItem> {

  @override
  Widget build(BuildContext context) {
    var entry = widget.nameKey.split('_');

    return Column(
      children: <Widget>[
        Container(
          padding: EdgeInsets.symmetric(horizontal: 10, vertical: 0),
          width: double.infinity,
          decoration: BoxDecoration(
            color: Color(0xFF343951),
            borderRadius: BorderRadius.circular(10)
          ),
          child: Theme(
            data: ThemeData(
              unselectedWidgetColor: Color(0xFF74A93A),
              accentColor: Color(0xFFF9C100),
            ),
            child: ExpansionTile(
              title: CustomText( title: entry[1], fontColor: Color(0xFF71798C), fontSize: 18 ),
              subtitle: CustomText( title: entry[0], fontColor: Colors.white70, fontSize: 12 ),
              backgroundColor: Color(0xFF343951),
              initiallyExpanded: false,
              children: <Widget>[
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 10, vertical: 0),
                  width: double.infinity,
                  height: 300,
                  child: SafeArea(
                      child: PageView(
                        children: <Widget>[
                          Container( 
                            child: ListView(
                              children: <Widget>[
                                Padding(
                                  padding: EdgeInsets.symmetric( horizontal: 0, vertical: 0),
                                  child: LineGraph(data: widget.data, index: widget.index),
                                ),
                              ],
                            ),
                          )
                        ],
                      )
                    ),
                )
              ],
            ),
          )
        ),
        SizedBox(height: widget.bottom,)
      ],
    );
  }
}

На самом деле работает нормально, моя проблема в том, что я передаю данные из этого виджета в line_graph

import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:tekax/widgets/custom_text.dart';

class LineGraph extends StatefulWidget {
  Map data;
  int index;

  LineGraph({ Key key, @required this.data, @required this.index });
  @override
  _LineGraphState createState() => _LineGraphState();
}

class _LineGraphState extends State<LineGraph> {

  _prepareData(){
    print("Data receiving ${widget.data[widget.index]}");
  }

  @override
  Widget build(BuildContext context) {  

    _prepareData();

    return ...
  }
}

Проблема два: _prepareData всегда получает ноль, я пытаюсь разными способами без ожидаемого результата uu

У вас есть идеи для решения моих проблем? Это мое первое приложение во флаттере извините

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...