dart _CastError(类型'Null'不是类型转换中类型'Map〈String,dynamic>'的子类型)Flutter

vbkedwbf  于 2023-03-21  发布在  Flutter
关注(0)|答案(2)|浏览(175)

我正在从FireStore收集数据,但这显示了问题。
我在努力-

class _HomePageState extends State<HomePage> {
  AuthClass authClass = AuthClass();
  final FirebaseAuth auth = FirebaseAuth.instance;

  @override
  Widget build(BuildContext context) {
    String st = "ToDo${auth.currentUser?.uid}";
    final Stream<QuerySnapshot> stream =
        FirebaseFirestore.instance.collection(st).snapshots();

    return Scaffold(
      backgroundColor: Colors.black87,
      appBar: AppBar(
        backgroundColor: Colors.black87,
        title: Text(
          "Today's Schedule",
          style: TextStyle(
            fontSize: 34,
            fontWeight: FontWeight.bold,
            color: Colors.white,

..........................................................................................................................

body: StreamBuilder(
          stream: stream,
          builder: (context, snapshot) {
            return ListView.builder(
                itemCount: snapshot.data?.docs.length,
                itemBuilder: (context, index) {
                  IconData iconData;
                  Color iconColor;
                  Map<String, dynamic> document =
                      snapshot.data?.docs[index].data() as Map<String, dynamic>;
                  switch (document["Category"]) {
                    case "Work":
                      iconColor = Colors.red;
                      iconData = Icons.run_circle_outlined;
                      break;
                    case "WorkOut":
                      iconColor = Colors.teal;
                      iconData = Icons.alarm;
                      break;

Firestore上有可用的数据,但它仍然显示Null子类型。我的应用程序正在工作,但在某些时候它会给出错误。

qybjjes1

qybjjes11#

这可能是由于两个原因。
第一种方法是在流的initialData中添加一个流类型的数据。
第二个是在您的snapShot.data包含null值。检查从错误控制台,并可以在模型文件中修复例如:像这样。

2j4z5cfb

2j4z5cfb2#

我有答案了。

body: StreamBuilder(
          stream: stream,
          builder: (context, snapshot) {
            return ListView.builder(
                itemCount: snapshot.data?.docs.length,
                itemBuilder: (context, index) {
                  IconData iconData;
                  Color iconColor;
                  Map<String, dynamic?> document =
                      snapshot.data?.docs[index].data() as Map<String, dynamic?>;
                  switch (document["Category"]) {
                    case "Work":
                      iconColor = Colors.red;
                      iconData = Icons.run_circle_outlined;
                      break;
                    case "WorkOut":
                      iconColor = Colors.teal;
                      iconData = Icons.alarm;
                      break;
Map<String, dynamic?> document =   snapshot.data?.docs[index].data() as Map<String, dynamic?>;

此处在动态i中声明为可空值,然后运行。

相关问题