Firebase数据不能在flutter应用程序中获取



我正在开发一个简单的应用程序来学习firebase,数据的创建工作得很好,但他们无法获取创建的数据。没有错误显示。只是在工作snapshot.hasError。我不知道代码有什么问题。

这是我的所有代码

首页


class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final user = FirebaseAuth.instance.currentUser;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('All User'),
),
body: StreamBuilder<List<Users?>>(
initialData: null,
stream: readUsers(),
builder: (context, snapshot) {
try {
log('no error on first hand');
if (snapshot.hasError) {
return const Center(
child: Text('something went wrong'),
);
} else if (snapshot.data == null) {
return const Text('No User Found');
} else if (snapshot.hasData) {
final users = snapshot.data!;
return ListView(
children: users.map(buildUsers).toList(),
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
} on FirebaseException catch (e) {
log('Error caught : $e');
return const Text('Server Crashed');
}
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const AddUserScreen(),
),
);
},
child: const Icon(Icons.add),
),
);
}
}

buildUser函数
Widget buildUsers(Users? user) => ListTile(
leading: CircleAvatar(child: Text('${user!.age}')),
title: Text(user.name),
subtitle: Text(user.sex),
);

readUser函数
Stream<List<Users>> readUsers() =>
FirebaseFirestore.instance.collection('users').snapshots().map((snapshot) =>
snapshot.docs.map((doc) => Users.fromJson(doc.data())).toList());

用户模型类

class Users {
String id;
final String name;
final int age;
final String sex;
Users({
this.id = '',
required this.name,
required this.age,
required this.sex,
});
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
'age': age,
'sex': sex,
};
static Users fromJson(Map<String, dynamic> json) => Users(
id: json['id'],
age: json['age'],
name: json['name'],
sex: json['sex'],
);
}

这些是所有的代码,谢谢你的时间

谢谢大家,我找到问题所在了

snapshot have connectionstate。所以我将代码设置为

StreamBuilder(
stream: stream,
builder: (context, snapshot) {
// Check for errors
if (snapshot.hasError) {
return SomethingWentWrong();
}
// Once complete, show your application
if (snapshot.connectionState == ConnectionState.done) {
// here you should do your worj
}
// Send updates to the widget
if (snapshot.connectionState == ConnectionState.active) {
// or here if you take data in pages
}
// Otherwise, show something whilst waiting for initialization to complete
return LoadingWidget();
},
);

this works fine

最新更新