【问题标题】:Getting data from cloud firestore onto a listview in flutter在颤动中将数据从云火库获取到列表视图
【发布时间】:2019-05-19 14:27:40
【问题描述】:

我正在尝试将数据从 firebase cloud firestore 集合(事件)提取到列表视图中,我不确定我是否正确实现了这一点,当我运行应用程序时出现错误“MappedListIterable”不是'Widget' 类型的子类型。这是我第一次使用 firebase cloud firestore,我真的可以使用一些帮助来更好地理解这个错误。

这是初始化列表视图的地方:

    import 'package:flutter/material.dart';
import 'package:rallie_app/utils/event_summary.dart';
import 'package:cloud_firestore/cloud_firestore.dart';


class HomeList extends StatelessWidget {

 Firestore db = Firestore.instance; 



  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: StreamBuilder<QuerySnapshot>(
          stream: Firestore.instance.collection('events').snapshots(),
          builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
           // count of events
            final int eventCount = snapshot.data.documents.length;
            if (snapshot.hasError)
              return new Text('Error: ${snapshot.error}');
            switch (snapshot.connectionState){
              case ConnectionState.waiting:
                return Center(child: CircularProgressIndicator());
              default:
                return new ListView.builder(
                    itemCount: eventCount ,
                  itemBuilder: (context, index) {
                    final DocumentSnapshot document = snapshot.data.documents[index];
                  return  new EventSummary(document);
                  }
                );
            }
          })



    );
  }
}

这些是我希望构建的列表视图项:

     import 'package:flutter/material.dart';
import 'package:rallie_app/model/events.dart';
import 'package:rallie_app/ui/detail/detail_page.dart';
import 'package:rallie_app/services/firestore_service.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';

class EventSummary extends StatefulWidget {
  //TODO: Event summary constructor with event model class initialized in it

  final DocumentSnapshot event;

  EventSummary(this.event);

  @override
  _EventSummaryState createState() => _EventSummaryState();
}

class _EventSummaryState extends State<EventSummary> {
  @override
  Widget build(BuildContext context) {
    final userThumbnail = new Container(
      margin: EdgeInsets.symmetric(vertical: 16.0),
      alignment: FractionalOffset.centerLeft,
      child: Hero(
        tag: "user-image-${widget.event.data['id']}",
        child: CircleAvatar(
          backgroundImage: AssetImage(widget.event['event_poster_image']),
          // backgroundColor: Colors.white,
          maxRadius: 40.0,
        ),
      ),
    );

    final eventCardContent = Container(
      margin: new EdgeInsets.only(left: 46.0),
      decoration: new BoxDecoration(
        shape: BoxShape.rectangle,
        color: new Color(0xFFFFFFFF),
        borderRadius: new BorderRadius.circular(8.0),
        image: DecorationImage(
          image: AssetImage(widget.event.data['event_image']),
          fit: BoxFit.fill,
        ),
      ),
    );

    Widget _eventValue(){
      return Column(
        children: <Widget>[
          Container(
            height: 150.0,
            margin: const EdgeInsets.symmetric(
              vertical: 16.0,
              horizontal: 24.0,
            ),
            child: new Stack(
              children: <Widget>[
                eventCardContent,
                userThumbnail,
              ],
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 70.0, bottom: 20.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  widget.event.data['event_name'],
                  textAlign: TextAlign.start,
                ),
                Row(
                  //crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      widget.event.data['event_date'],
                      textAlign: TextAlign.start,
                    ),
                    SizedBox(
                      width: 110,
                    ),
                    IconButton(
                      icon: Icon(Icons.share),
                      splashColor: Colors.orange,
                      tooltip: 'Share button',
                      onPressed: () =>
                          debugPrint('Share btn tapped'),
                    )
                  ],
                ),
                Text(
                  widget.event.data['event_attending'],
                  textAlign: TextAlign.start,
                ),
              ],
            ),
          )
        ],
      );
    }

    return new GestureDetector(
      onTap: () => Navigator.of(context).push(
            new PageRouteBuilder(
              pageBuilder: (_, __, ___) => new DetailPage(widget.event.data['id']),
              transitionsBuilder:
                  (context, animation, secondaryAnimation, child) =>
                      new FadeTransition(opacity: animation, child: child),
            ),
          ),
      child: StreamBuilder(
          stream: Firestore.instance.collection('events').snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) return Text('Loading data... Please wait');
            return snapshot.data.documents.map(
              (document) => _eventValue()
            );
          }),
    );
  }
}

【问题讨论】:

    标签: firebase dart flutter google-cloud-firestore


    【解决方案1】:

    在您的代码中 - 编辑 - widget.event['id'] 到 - widget.event.data['id'] & So On 与您使用 Snapshot 变量的其他地方相同...

    根据文档 - DocumentSnapshot

    DocumentSnapshot 包含从云中的文档读取的数据 Firestore 数据库。可以使用 .data() 提取数据

    widget.event是-DocumentSnapshot&读取数据需要使用.data方法。

    你得到的错误也是代码:

    child: StreamBuilder(
              stream: Firestore.instance.collection('events').snapshots(),
              builder: (context, snapshot) {
                if (!snapshot.hasData) return Text('Loading data... Please wait');
                return snapshot.data.documents.map(
                  (document) => Column(
                                  ......
    

    这里 Builder 期望 Widget 作为返回值而不是 'MappedListIterable' -

    snapshot.data.documents.map(
                      (document) // is Wrong return value for StreamBuilder.
    

    您需要修改代码才能在此处返回小部件。

    【讨论】:

    • 所以我创建了一个小部件类型的方法,该方法返回列并将该方法作为流构建器的返回值调用,但我仍然认为“MappedListIterable”不是子类型'Widget' 类型错误已在我上面的代码中更新
    • 您仍在返回 - snapshot.data.documents.map - 这将永远无法正常工作。此代码返回 MappedListIterable 不是任何 Widget。
    • 感谢您的帮助!
    猜你喜欢
    • 2022-08-22
    • 2021-08-11
    • 2021-04-09
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 2017-11-09
    • 2020-12-24
    • 1970-01-01
    相关资源
    最近更新 更多