gpt4 book ai didi

flutter - Flutter:失败的断言: bool 表达式不能为空

转载 作者:行者123 更新时间:2023-12-03 03:21:20 24 4
gpt4 key购买 nike

在 flutter 朔迷离中,我使用Future从Firestore云数据库中调用了一个值,然后尝试将此值分配给变量。

Here is my code:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class Gyanpothro extends StatefulWidget {
@override
_GyanpothroState createState() => _GyanpothroState();
}

class _GyanpothroState extends State<Gyanpothro> {
Firestore db = Firestore.instance;
Future databaseFuture;
@override
void initState() {
databaseFuture = db.collection('notice').document('0').get();
super.initState();
}

@override
Widget build(BuildContext context) {
return FutureBuilder(
future: databaseFuture,
builder: (context, snapshot) {
if (!snapshot.data) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
LinearProgressIndicator(
backgroundColor: Colors.amber,
),
Text("Loading"),
],
);
}
var _notice = snapshot.data.data['notice'];
var _heading = snapshot.data.data['heading'];
print(_notice);

return Text(_notice);
});
}
}
但是我在使用 future builder 时遇到错误- Another exception was thrown: Failed assertion: boolean expression must not be null 问题出在哪里。我该如何解决呢?

最佳答案

问题出在FutureBuilder代码中。要检查data是否已到达,请检查错误的标志。检查snapshot.hasData而不是snapshot.data

    @override
Widget build(BuildContext context) {
return FutureBuilder(
future: databaseFuture,
builder: (context, snapshot) {
if (snapshot.hasData) {
// Data is avialable. call snapshot.data
}
else if(snapshot.hasError){
// Do error handling
}
else {
// Still Loading. Show progressbar
}
});
}

关于flutter - Flutter:失败的断言: bool 表达式不能为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62874312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com