首页 > 解决方案 > _TypeError 在使用 Cloud Firestore 时出现 Flutter

问题描述

我收到此错误:

以下 _TypeError 被抛出构建:

type '() => Map<String, dynamic>' 不是类型 'Map<dynamic, dynamic>' 的子类型

When the exception was thrown, this was the stack: 
#0      FirestoreSlideshowState.build.<anonymous closure>.<anonymous closure> (package:mypackagename/main.dart:78:51)
#1      SliverChildBuilderDelegate.build (package:flutter/src/widgets/sliver.dart:449:22)
#2      SliverMultiBoxAdaptorElement._build (package:flutter/src/widgets/sliver.dart:1130:28)
#3      SliverMultiBoxAdaptorElement.performRebuild.processElement (package:flutter/src/widgets/sliver.dart:1076:66)
#4      Iterable.forEach (dart:core/iterable.dart:283:30)

我正在使用 Cloud Firestore 将数据加载到我的 PageView 应用程序中。

这是我的数据库结构。

这是我的 main.dart 中的完整代码,这给了我错误。

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {

  return MaterialApp(
      home: Scaffold(body: FirestoreSlideshow())
  );
}
}

class FirestoreSlideshow extends StatefulWidget {
  createState() => FirestoreSlideshowState();
}

class FirestoreSlideshowState extends State<FirestoreSlideshow> {

  final PageController ctrl = PageController(viewportFraction: 0.8);

  final FirebaseFirestore db = FirebaseFirestore.instance;
  Stream slides;


  String activeTag = 'all';

  // Keep track of current page to avoid unnecessary renders
  int currentPage = 0;


  @override
  void initState() {
    _queryDb();

    // Set state when page changes
    ctrl.addListener(() {
      int next = ctrl.page.round();

      if(currentPage != next) {
        setState(() {
          currentPage = next;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
        stream: slides,
        initialData: [],
        builder: (context, AsyncSnapshot snap) {

          List slideList = snap.data.toList();

          return PageView.builder(

              controller: ctrl,
              itemCount: slideList.length + 1,
              itemBuilder: (context, int currentIdx) {


                if (currentIdx == 0) {
                  return _buildTagPage();
                } else if (slideList.length >= currentIdx) {
                  // Active page
                  bool active = currentIdx == currentPage;
                  return _buildStoryPage(slideList[currentIdx - 1], active);
                }
                return null;
              }
          );
        }
    );
  }

  Stream _queryDb({ String tag ='all' }) {

    // Make a Query
    Query query = db.collection('Articles').where('tags', arrayContains: tag);

    // Map the documents to the data payload
    slides = query.snapshots().map((list) => list.docs.map((doc) => doc.data));

    // Update the active tag
    setState(() {
      activeTag = tag;
    });

  }


  // Builder Functions

  _buildStoryPage(Map data, bool active) {
    // Animated Properties
    final double blur = active ? 30 : 0;
    final double offset = active ? 20 : 0;
    final double top = active ? 100 : 200;


    return AnimatedContainer(
        duration: Duration(milliseconds: 500),
        curve: Curves.easeOutQuint,
        margin: EdgeInsets.only(top: top, bottom: 50, right: 30),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20),

            image: DecorationImage(
              fit: BoxFit.cover,
              image: NetworkImage(data['image']),
            ),

            boxShadow: [BoxShadow(color: Colors.black87, blurRadius: blur, offset: Offset(offset, offset))]
        ),
        child: Center(
            child: Text(data['name'], style: TextStyle(fontSize: 40, color: Colors.white))
        )
    );
  }


  _buildTagPage() {
    return Container(child:
    Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.start,

      children: [
        Text('Your Stories', style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold),),
        Text('FILTER', style: TextStyle( color: Colors.black26 )),
        _buildButton('all'),
        _buildButton('india'),
        _buildButton('howto')
      ],
    )
    );
  }

  _buildButton(tag) {
    Color color = tag == activeTag ? Colors.purple : Colors.white;
    return FlatButton(color: color, child: Text('#$tag'), onPressed: () => _queryDb(tag: tag));
  }

}

标签: firebaseflutterdartgoogle-cloud-firestore

解决方案


推荐阅读