[英]Firebase data is not fetching in flutter app
我正在开发一个简单的应用程序来学习 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),
),
);
}
}
Widget buildUsers(Users? user) => ListTile(
leading: CircleAvatar(child: Text('${user!.age}')),
title: Text(user.name),
subtitle: Text(user.sex),
);
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'],
);
}
这些是所有代码,谢谢你的时间
谢谢你们的时间,我想出了问题是什么
快照有连接状态。 所以我这样设置代码
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();
},
);
这很好用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.