Home > OS >  Why is my firebase database not reading anything in flutter?
Why is my firebase database not reading anything in flutter?

Time:10-23

This is the main.dart file, I made a StreamBuilder which accepts value of users which is a model class.

But when it starts reading , it doesn't and it straight goes to the something went wrong else if block.

The model class is a converts map to json and json to <List> but i dont seem to get where it went wrong.

This project i was following from Johannes Milke on YouTube I have followed the same steps but can't seem to fix this error.

I can create files with it but reading is being an issue.

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  final controller = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      floatingActionButton: IconButton(
        icon: Icon(Icons.add),
        onPressed: (){
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => const UserInfo(),
            ),
          );
        },
        color: Colors.blue,
      ),
      body: StreamBuilder<List<User>>(
        stream: readUsers(),
        builder: (context,snapshot){
          if(snapshot.hasError){
            return Text('Something Went Wrong',style: TextStyle(color: Colors.white),);
          }
          else if(snapshot.hasData){
            final users = snapshot.data!;
            return ListView(
              children: users.map(buildUser).toList(),
            );
          }
          else{
            return Center(child: CircularProgressIndicator(),);
          }
        }
      ),

      );

  }
  Widget buildUser(User user)=>ListTile(
    leading: CircleAvatar(child: Text('${user.age}'),),
    title: Text(user.name,style: TextStyle(color:Colors.white),),
    subtitle: Text(user.birthday.toIso8601String()),
  );
Stream<List<User>> readUsers()=> FirebaseFirestore.instance.collection('users').snapshots().map(
        (snapshot)=>snapshot.docs.map((doc)=>User.fromJson(doc.data())).toList()
);

This is the model class,


    import 'dart:convert';
    
    import 'package:cloud_firestore/cloud_firestore.dart';
    
    class User{
      String id;
      final String name;
      final int age;
      final DateTime birthday;
      User({
        this.id=' ',
        required this.name,
        required this.age,
        required this.birthday
      });
      Map<String,dynamic> toJson()=>{
        'id':id,
        'name':name,
        'age':age,
        'birthday':birthday,
      };
      static User fromJson(Map<String,dynamic>json)=>User(
    
          id: json['id'],
          name: json['name'],
          age: json['age'],
          birthday: (json['birthday'] as Timestamp).toDate()
    
    
          );
    }

This error pops up

CodePudding user response:

There can be probably an issue with firestore rules, the following read security rule should do the trick:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
     match /{document=**} {
    allow read, write: if true
    }
    
  
  }
}

Note: It is for testing purposes. In production, that is not true to apply this kind of security rule in your firestore.

  • Related