List.Builder дает ошибку диапазона в Flutter - PullRequest
0 голосов
/ 19 апреля 2020

Я добавил весь свой код здесь. Метод getRecords требует больше времени для добавления в списки, и, следовательно, мой список сначала возвращается пустым, и поэтому построитель списков не может выдать ошибку диапазона, а принятый диапазон - только 0. Кстати, это приложение Todo.

InitState:

void initState() {
super.initState();
setState(() {
getRecords();
 });
}

Получение из базы данных

void getRecordsAndDisplay() async {
final records = await Firestore.instance.collection('tasks').getDocuments();
for (var record in records.documents) {
  if (record.data['phone'] == '1') {
    int len = record.data['task'].length;
    if (len != null || len != 0) {
      for (int i = 0; i < len; i++) {
        String temp = record.data['task'][i];
        tasks.add(temp);
      }
    }
    else
      continue;
  }
  else
    continue;
}
setState(() {
  listView = ListView.builder(
    scrollDirection: Axis.vertical,
    itemCount: tasks.length,
    itemBuilder: (BuildContext context,int index) {
      return Container(
        margin: EdgeInsets.only(bottom: 10.0),
        decoration: BoxDecoration(
          color: Colors.deepPurple[700],
          borderRadius: BorderRadius.all(Radius.circular(20.0)),
        ),
        child: ListTile(
          onTap: (){},
          leading: IconButton(
            icon: Icon(Icons.delete),
            iconSize: 25.0,
            color: Colors.white,
            onPressed: () {
              setState(() {
                tasks.removeAt(index);
                checkValue.removeAt(index);
                updateValue();
              });
            },
          ),
          title: Text(
            '${tasks[index]}',
            style: TextStyle(
              fontSize: 18.0,
              color: Colors.white,
              fontWeight: FontWeight.bold,
              decoration: checkValue[index]
                  ? TextDecoration.lineThrough
                  : null,
            ),
          ),
          trailing: Checkbox(
            value: checkValue[index],
            activeColor: Colors.white,
            checkColor: Colors.deepPurple[700],
            onChanged: (bool value) {
              setState(() {
                checkValue[index] = !checkValue[index];
              });
            },
          ),
        ),
      );
    },
  );
});

}

Эшафот:

return Scaffold(
  backgroundColor: Color(0xff8780FF),
  body: SafeArea(
    child: Container(
      decoration: BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.topRight,
              colors: [Colors.deepPurple[400], Color(0xff6B63FF)])),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                padding: EdgeInsets.fromLTRB(30.0, 30.0, 30.0, 15.0),
                decoration: BoxDecoration(boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.2),
                    spreadRadius: 1.0,
                    blurRadius: 50.0,
                  ),
                ]),
                child: Icon(
                  Icons.list,
                  color: Colors.white,
                  size: 30.0,
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.only(
                      bottom: 20.0,
                      left: 30.0,
                    ),
                    child: Text(
                      'Todo List',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 35.0,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                  ),
                  Expanded(
                    child: SizedBox(
                      width: 20.0,
                    ),
                  ),
                  IconButton(
                    padding: EdgeInsets.only(
                      right: 10.0,
                      bottom: 20.0,
                    ),
                    icon: Icon(Icons.add),
                    iconSize: 30.0,
                    color: Colors.white,
                    onPressed: () async {
                      final resultText = await showModalBottomSheet(
                          context: context,
                          builder: (context) => AddTaskScreen(),
                          isScrollControlled: true);
                      setState(() {
                        tasks.add(resultText);
                        checkValue.add(false);
                        Firestore.instance
                            .collection('tasks')
                            .document('1')
                            .updateData({
                          'task': FieldValue.arrayUnion([resultText]),
                        });
                      });
                    },
                  ),
                  IconButton(
                    padding: EdgeInsets.only(
                      right: 10.0,
                      bottom: 20.0,
                    ),
                    icon: Icon(Icons.delete_outline),
                    iconSize: 30.0,
                    color: Colors.white,
                    onPressed: () {
                      setState(() {
                        tasks.clear();
                        checkValue.clear();
                        Firestore.instance
                            .collection('tasks')
                            .document('1')
                            .updateData({
                          'task': null,
                        });
                      });
                    },
                  ),
                ],
              ),
            ],
          ),
          Flexible(
            child: Container(
              padding: EdgeInsets.only(left: 10.0, right: 10.0),
              height: MediaQuery.of(context).size.height,
              child: listView,
            ),
          ),
        ],
      ),
    ),
  ),
);

Пожалуйста, помогите мне. Я застрял с этим в течение длительного времени: (

1 Ответ

0 голосов
/ 19 апреля 2020

проблема в том, что в initstate вы не можете ожидать asyn c методов, поэтому вы должны реализовать StreamBuilder, который оборачивает ваше представление списка. Streambuilder - это виджет, который принимает поток и ожидает завершения вызова тогда, когда данные хорошо показывает виджет -> ваш список

небольшой пример

StreamBuilder(
    stream: YOUR_ASYNC_CALL_THAT_RETURN_A_STREAM,
    builder: (context, snapshot) {
        if (!snapshot.hasData) {
            return Container(
                alignment: Alignment.center,
                child: Text(
                    "NO ITEMS"
                ),
            );
        } 
        else {
            var yourList = snapshot.data.documents;//there you have to do your implementation
            return ListView.builder(
                itemBuilder: (context, index) => buildItem(index,yourList[index]),
                itemCount: yourList.length,
            );
        }
    },
),
...