我是 Flutter 的新手。我正在尝试通过 Stream 从 Firestore 获取数据。但它给了我错误。我试图获取一个字符串和一个列表,但我不知道在代码中更改什么来获取列表。在代码中,'name'
字段是字符串,'overview'
字段是列表。
import 'package:firebaseAuth/firebaseAuthDemo.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class FindDiseases extends StatefulWidget {
final User user;
const FindDiseases({Key key, this.user}) : super(key: key);
@override
_FindDiseasesState createState() => _FindDiseasesState();
}
class _FindDiseasesState extends State<FindDiseases> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
FirebaseAuth _auth = FirebaseAuth.instance;
List diseasesList = [];
dynamic data;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.teal,
//automaticallyImplyLeading: false,
title: Text(
"Diseases List",
),
),
key: _scaffoldKey,
body: Container(
color: Colors.white,
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection("diseases")
.orderBy('id')
.snapshots(),
builder: (context, snapshot) {
return ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context, index) {
DocumentSnapshot user = snapshot.data.docs[index];
return Card(
color: Colors.white,
child: FlatButton(
onPressed: () {},
child: ListTile(
title: Text(user['name']),
subtitle: Text(user['overview']),
),
),
);
},
);
},
),
),
);
}
数据如下所示:
"name": "Agoraphobia",
"overview": "[
'Losing weight.', 'Stopping medications or supplements.', 'Having surgery.'
]"
答案 0 :(得分:0)
那是因为你正在使用
subtitle: Text(user['overview']),
作为字符串,而在数据中,此数据为列表格式,尝试从中获取索引数据,然后尝试显示为字符串
答案 1 :(得分:0)
在您的数据中,“概览”是一种列表类型,您正试图将其作为字符串获取。
List<String> list = user['overview'];
String data = String.join(", ", list);
return Card(
color: Colors.white,
child: FlatButton(
onPressed: () {},
child: ListTile(
title: Text(user['name']),
subtitle: Text(data),
),
),
);