简体   繁体   中英

Flutter Firestore: How to retrieve map data from Firestore and display in Flutter Widget

How can I display map data from a collection in Firestore into a ListView Widget when expanded. I need to retrieve the quantity (int) and title fields (String) from the Firestore Collection and display it in a Row in my Flutter App. I am getting an error of type 'String' is not a subtype of type 'int' of 'index'

import 'package:intl/intl.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import '../providers/orders.dart' show Orders;
import 'package:provider/provider.dart';
import 'package:ionicons/ionicons.dart';

class OrdersScreen extends StatefulWidget {
  const OrdersScreen({Key? key}) : super(key: key);
  static const routeName = '/orders-screen';

  @override
  State<OrdersScreen> createState() => _OrdersScreenState();
}

class _OrdersScreenState extends State<OrdersScreen> {
  var _expanded = false;

  @override
  Widget build(BuildContext context) {
    Provider.of<Orders>(context, listen: false);
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Theme.of(context).primaryColor,
        title: const Text(
          'Order History',
        ),
      ),
      body: StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance
            .collection('orders')
            .orderBy('date', descending: true)
            .snapshots(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          } else {
            if (snapshot.error != null) {
              return const Center(
                child: Text('An error has occured'),
              );
            } else {
              return ListView(
                  children: snapshot.data!.docs.map((doc) {
                return Card(
                  margin: const EdgeInsets.all(10.0),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(15.0),
                  ),
                  child: Column(
                    children: [
                      ListTile(
                        title: Text(
                          'R' + doc['total'],
                          style: const TextStyle(fontWeight: FontWeight.bold),
                        ),
                        subtitle: Text(
                          DateFormat('dd/MM/yyyy hh:mm a').format(
                            doc['date'].toDate(),
                          ),
                        ),
                        trailing: IconButton(
                          icon: Icon(
                            _expanded
                                ? Ionicons.chevron_up
                                : Ionicons.chevron_down,
                            color: Colors.blueGrey[900],
                          ),
                          onPressed: () {
                            setState(() {
                              _expanded = !_expanded;
                            });
                          },
                        ),
                      ),
                      if (_expanded)
                        (SizedBox(
                          height: 100.0,
                          child: ListView(
                            children: [
                              Row(
                                children: [
                                  Text(
                                    doc['orderDetails']['quantity'].toString(),
                                  ),
                                  Text(
                                    doc['orderDetails']['title'],
                                  ),
                                ],
                              ),
                            ],
                          ),
                        )),
                    ],
                  ),
                );
              }).toList());
            }
          }
        },
      ),
    );
  }
}

在此处输入图像描述

The quantity is coming back as an int but You passed it directly to a Text which expects a String

Try:

ListView(
    children: List.generate(
      List.from(doc['orderDetails').length,
      (i) {
       return Row(
        children: [
          Text(doc['orderDetails'][i]['quantity'].toString()),
          Text(doc['orderDetails'][i]['title'].toString())),
        ],
      );
    )
)

Here orderDetails is not the Map<String, dynamic> - it's a list of Map<String, dynamic> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM