我是该语言的初学者,我不知道该如何处理。我想要的这段代码是getDocs()函数将从firestore中取出数据。发生这种情况后,statefull小部件将从列表中构建文本,该列表将包含来自Firestore的数据。错误显而易见,表明我的列表为空:Error from device
我的代码如下:
class TestBasic extends StatefulWidget {
int time;
int amount;
TestBasic({this.time, this.amount});
@override
_TestBasicState createState() => _TestBasicState();
}
class _TestBasicState extends State<TestBasic> {
List<Map> listOfQuestionsMap = [];
List<Question> listOfQuestions = [];
Future getDocs() async {
QuerySnapshot querySnapshot =
await Firestore.instance.collection("questions").getDocuments();
for (int i = 0; i < widget.amount; i++) {
var a = querySnapshot.documents[i];
listOfQuestionsMap.add(a.data);
}
List<Question> listOfQuestionsQ = listOfQuestionsMap.map((doc) {
return Question(
answer: doc['answer'] ?? '',
questionText: doc['questionText'] ?? '',
type: doc['type'] ?? '',
substantiation: doc['substantiation'] ?? '',
article: doc['article'] ?? ''
);
}).toList();
print(listOfQuestionsQ[1].answer);
setState(() {
listOfQuestions.addAll(listOfQuestionsQ);
});
}
@override
void initState() {
getDocs();
super.initState();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 40.0),
child: Container(
alignment: Alignment.center,
height: Responsive.height(40, context),
decoration: BoxDecoration(
border: Border.all(color: Colors.black, width: 1.0)),
child: Text(listOfQuestions[0].answer,
textAlign: TextAlign.center,
style: TextStyle(
decoration: TextDecoration.none,
color: Colors.black,
fontSize: 20.0,
)),
),
);
有问题模型:
class Question {
final String type;
final String questionText;
final String answer;
final String substantiation;
final String article;
Question({this.answer, this.questionText, this.type, this.substantiation, this.article});
}
有人可以向我解释如何获得我想要的结果吗?
答案 0 :(得分:1)
您收到该错误是因为build
是在getDocs
更新列表之前被调用的,而您的listOfQuestions
为空,并且您尝试在索引(0)处获取了一个值。
尝试使用:
Text(
listOfQuestions.isEmpty ? "Loading" : listOfQuestions[0].answer
)
这样,当listOfQuestions
为空时,Text
显示正在加载,而当listOfQuestions
有数据时,它将显示listOfQuestions[0].answer
的值