简体   繁体   中英

Firebase data is not fetching in flutter app

I'm developing a simple app to learn firebase, the creation of data is working fine, but they can't fetch the created data. and there is no error showing. just working the snapshot.hasError . I've no idea what's wrong with the code.

here is my all code

HomePage


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 function

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

readUser Function

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

User model class

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'],
      );
}

these are the all codes, thank you for your time

thank you guys for your time, I figured out what the problem is

snapshot have connectionstate. so I set the code like this

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 worked fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM