简体   繁体   English

尝试使用 flutter 访问 Firebase 上的列表时,在 Null 错误上调用获取 getter 长度

[英]Getting a getter length is called on Null error when trying to access List on Firebase using flutter

I am trying to retrieve and display a list of items on firebase, I have been able to access everything else on firebase apart from the list itself.我正在尝试检索并显示 firebase 上的项目列表,除了列表本身之外,我已经能够访问 firebase 上的所有其他内容。 I think the issue might be how I am going about retrieving the list because of the method in which it was saved.我认为问题可能是我将如何检索列表,因为它的保存方法。 Here is the order model code这是订单 model 代码

import 'package:butcherbox/models/productsModel.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:meta/meta.dart';

class Order {
  Order(
      {@required this.items,
      //this.theItems,
      this.location,
      this.orderId,
      this.time,
      @required this.price});

  final List<ProductsModel> items;
  final String location;
  final int orderId;
  final Timestamp time;
  final int price;

  factory Order.fromMap(Map<String, dynamic> data) {
    if (data == null) {
      return null;
    }
    final List<ProductsModel> items = data['items'];
    final String location = data['location'];
    final int price = data['price'];
    final int orderId = data['orderId'];
    final Timestamp time = data['time'];

    return Order(
      items: items,
      location: location,
      price: price,
      orderId: orderId,
      time: time,
    );
  }


  Map<String, dynamic> toMap() {
    return {
      'item': items.map((e) => e.toJson()).toList(),
      'location': location,
      'orderId': orderId,
      'time': time,
      'price': price
    };
  }
}

This is the code to display the data这是显示数据的代码

import 'package:butcherbox/butch_widgets/order_list_tile.dart';
import 'package:butcherbox/models/ordersmodel.dart';
import 'package:butcherbox/services/database.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class Orders extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.green[200],
        title: Text(
          'Orders',
          textAlign: TextAlign.center,
          style: TextStyle(color: Colors.green[900]),
        ),
      ),
      body: _buildContents(context),
    );
  }

  Widget _buildContents(BuildContext context) {
    final database = Provider.of<Database>(context, listen: false);
    return StreamBuilder<List<Order>>(
        stream: database.ordersStream(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final orders = snapshot.data;
            // final children =
            // orders.map((order) => Text(order.location)).toList();
            final children =
                orders.map((order) => OrderListTile(order: order)).toList();
            return ListView(children: children);
          }
          if (snapshot.hasError) {
            return Center(child: Text('Some Error Occurred'));
          }
          return Center(child: CircularProgressIndicator());
        });
  }
}

This is the widget for the UI这是 UI 的小部件

import 'package:butcherbox/models/ordersmodel.dart';
import 'package:flutter/material.dart';

class OrderListTile extends StatelessWidget {
  final Order order;

  const OrderListTile({Key key, @required this.order}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(
        'Order No: ${order.orderId}',
        style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: Colors.green[900]),
      ),
      trailing: Text(
        'Vendor: ${order.location}',
        style: TextStyle(fontSize: 16),
      ),
      subtitle: ListView.builder(
          itemCount: order.items.length, <-- This is where the error is
          shrinkWrap: true,
          itemBuilder: (context, i) {
            return Expanded(
              child: Column(
                children: [
                  Text('${order.items[i].name}'),
                  Text('${order.items[i].quantity.toString()}')
                ],
              ),
            );
          }),
      isThreeLine: true,
    );
  }
}

This is the database code这是数据库代码

import 'package:butcherbox/models/ordersmodel.dart';
import 'package:butcherbox/services/api_path.dart';
import 'package:meta/meta.dart';
import 'package:butcherbox/services/firestore_service.dart';

abstract class Database {
  Future<void> createOrder(Order order);
  Stream<List<Order>> ordersStream();
}

String docFromId() => DateTime.now().toIso8601String();

class FireStoreDatabase implements Database {
  FireStoreDatabase({@required this.uid}) : assert(uid != null);
  final String uid;
  final _service = FireStoreService.instance;

  Future<void> createOrder(Order order) => _service.setData(
        //path: APIPath.order(uid, 'orderdetails'), data: order.toMap());
        path: APIPath.order(uid, docFromId()),
        data: order.toMap(),
      );

  Stream<List<Order>> ordersStream() => _service.collectionStream(
      path: APIPath.orders(uid), builder: (data) => Order.fromMap(data));
}
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/foundation.dart';

class FireStoreService {
  FireStoreService._();
  static final instance = FireStoreService._();

  Future<void> setData({String path, Map<String, dynamic> data}) async {
    final reference = FirebaseFirestore.instance.doc(path);
    print('$path: $data');
    await reference.set(data);
  }

  Stream<List<T>> collectionStream<T>({
    @required String path,
    @required T Function(Map<String, dynamic> data) builder,
  }) {
    final reference = FirebaseFirestore.instance.collection(path);
    final snapshots = reference.snapshots();
    return snapshots.map((snapshot) => snapshot.docs
        .map(
          (snapshot) => builder(snapshot.data()),
        )
        .toList());
  }
}

Yes actually you are right, so here are some keypoints,是的,实际上你是对的,所以这里有一些关键点,

  Stream<List<Order>> ordersStream() => _service.collectionStream(
      path: APIPath.orders(uid), builder: (data) => 
// This is supposed to be a list of Orders.
Order.fromMap(data));

You can try printing the data here so you see what I am talking about(it would be a List and not a singular object).您可以尝试在此处打印数据,以便了解我在说什么(它将是一个列表,而不是一个单一的对象)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未获取用户数据。 错误:在 null 上调用了吸气剂“uid” - Not Getting User Data. Error: The getter 'uid' was called on null 在 firebase 中使用 .where('uid', isEqualTo: uid) 时出现 null 错误 flutter - getting null error when using .where('uid', isEqualTo: uid) in firebase flutter Firebase function 尝试写入 firebase 存储“Firebase 存储:用户无权访问”时出错 - Firebase function getting error when trying to write to firebase storage "Firebase Storage: User does not have permission to access" NoSuchMethodError:在 null 上调用了吸气剂“docs”。Flutter - NoSuchMethodError: The getter 'docs' was called on null. Flutter 在 null 上调用了吸气剂“imgUrl” - The getter 'imgUrl' was called on null 尝试使用 Flutter Firebase 再次登录时,Google 登录包的断开连接方法调用导致错误 - Google Sign In package's disconnect method call results in error when trying to sign in again using Flutter Firebase Flutter/Firebase - 列表<dynamic>没有实例 getter 'documents'</dynamic> - Flutter/Firebase - List<dynamic> has no instance getter 'documents' Flutter/Dart/firebase:: 尝试注销时出错 - Flutter/Dart/firebase:: Error when trying to sign out 尝试访问文档字段时 Flutter/Firebase 中的额外位置参数 - Extra Positional Argument in Flutter/Firebase when trying to access document field Flutter - Firebase RTDB,在 null 上调用了 forEach 方法 - Flutter - Firebase RTDB, The method forEach was called on null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM