List.Builder在Flutter中给出范围错误

时间:2020-04-19 11:28:13

标签: flutter flutter-dependencies flutter-web flutter-test

我已经在这里添加了整个代码。 getRecords方法需要花费更多时间添加到列表中,因此我的列表首先返回空,因此listbuilder无法给出范围错误,并且只能接受的范围是0。BTW,它是一个Todo应用程序。

InitState:

async function f(){
  let result1 = await doSomeAction()
  let result2 = await sendMailIfSuccess()
}

try {
 f()
} catch(err) {
 //handle error
}

从数据库获取

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];
              });
            },
          ),
        ),
      );
    },
  );
});

请帮帮我。我坚持了很长时间:(

1 个答案:

答案 0 :(得分:0)

问题在于,在初始化状态下,您无法等待异步方法,因此您应该实现一个包装列表视图的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,
            );
        }
    },
),