我试图从 Firestore 数据库中使用 ListTile 列出一些数据。在从数据库中提取数据时,我得到了下面的异常。数据库中所有属性的名称和代码都相同。我不知道它为什么会抛出它。
The following assertion was thrown:
An exception was throw by _MapStream<QuerySnapshot<Map<String, dynamic>>, List<Stuff>> listened by
StreamProvider<List<Stuff>?>, but no `catchError` was provided.
Exception:
type 'int' is not a subtype of type 'String'
这是我的东西。飞镖:
class Stuff {
final String title;
final String details;
final String price;
Stuff({
required this.title,
required this.details,
required this.price,
});
}
这是我的database.dart:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:unistuff_main/models/stuff.dart';
class DatabaseService {
final String? uid;
DatabaseService({this.uid});
//collection reference
final CollectionReference stuffCollection =
FirebaseFirestore.instance.collection('stuffs');
//stufflist from snapshot
List<Stuff> _stuffListFromSnapshot(QuerySnapshot snapshot) {
return snapshot.docs.map((doc) {
return Stuff(
title: doc.get('title') ?? '0',
price: doc.get('price') ?? '0',
details: doc.get('details') ?? '0',
);
}).toList();
}
//get the stuffs
Stream<List<Stuff>> get stuffs {
return stuffCollection.snapshots().map(_stuffListFromSnapshot);
}
}
这是我的stuff_list.dart:
import 'package:flutter/material.dart';
import 'package:unistuff_main/models/stuff.dart';
import 'package:provider/provider.dart';
import 'package:unistuff_main/screens/home/stuff_tile.dart';
class StuffList extends StatefulWidget {
const StuffList({Key? key}) : super(key: key);
@override
_StuffListState createState() => _StuffListState();
}
class _StuffListState extends State<StuffList> {
@override
Widget build(BuildContext context) {
final stuffs = Provider.of<List<Stuff>?>(context);
//print(stuffs?.docs);
if (stuffs != null) {
stuffs.forEach((stuff) {
print(stuff.title);
print(stuff.details);
print(stuff.price);
});
}
return ListView.builder(
//number of the items in list
itemCount: stuffs?.length ?? 0,
//return a function for every item in the list
itemBuilder: (context, index) {
return StuffTile(stuff: stuffs![index]);
},
);
}
}
和stuff_tile.dart:
import 'package:flutter/material.dart';
import 'package:unistuff_main/models/stuff.dart';
class StuffTile extends StatelessWidget {
//const StuffGrid({ Key? key }) : super(key: key);
//sending the data to stuff
final Stuff? stuff;
StuffTile({this.stuff});
@override
Widget build(BuildContext context) {
//creating the list view
return Padding(
padding: EdgeInsets.only(top: 8.0),
child: Card(
margin: EdgeInsets.fromLTRB(20.0, 6.0, 20.0, 0.0),
child: ListTile(
leading: CircleAvatar(
radius: 25.0,
backgroundColor: Colors.brown,
),
title: Text(stuff!.title),
subtitle: Text(stuff!.details)
),
));
}
}
任何事情都会有帮助!