Home > Back-end >  Flutter Firebase accessing id in Field
Flutter Firebase accessing id in Field

Time:07-13

I am writing a new application and I have transferred the followers to the field in users. How can I access the id in the field and list the user photo and username?

enter image description here

CodePudding user response:

final documentSnapshot = await FirebaseFirestore.instance.doc('collection_name/doc_Id').get();

/// (In your case 'field_name' is 'followers')
final _fieldDataCollection = documentSnapshot.data()['field_name']

That's how you can get a particular field value. Now fetch user details, with that required id.

CodePudding user response:

It should be something like the following prototype code:

Future<List<User>> getFollowers(String uid) async {
  final users = FirebaseFirestore.instance.collection('users');
  final doc = await users.doc(uid).get();
  final followerIds = List.from(doc['followers']);
  return followerIds.map((uid) => User.fromSnap(await users.doc(uid).get()));
}

CodePudding user response:

My codes are as follows. But I need to list the uid information in the field. What changes do I need to make?

followers.screen.dart

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

  @override
  State<FollowersScreen> createState() => _FollowersScreenState();
}

class _FollowersScreenState extends State<FollowersScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: mobileBackgroundColor,
        centerTitle: true,
        title: Image.asset(
          'Resim/logo.png',
          height: 50,
        ),
      ),
      body: StreamBuilder(
        stream: FirebaseFirestore.instance.collection('users').snapshots(),
        builder: (context,
            AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
          return ListView.builder(
            itemCount: snapshot.data!.docs.length,
            itemBuilder: (context, index) => FollowersCard(
              snap: snapshot.data!.docs[index].data(),
            ),
          );
        },
      ),
    );
  }
}

followers_card.dart

class FollowersCard extends StatefulWidget {
  final snap;

  const FollowersCard({
    Key? key,
    required this.snap,
  }) : super(key: key);

  @override
  State<FollowersCard> createState() => _FollowersCardState();
}

class _FollowersCardState extends State<FollowersCard> {
  

  @override
  void initState() {
    super.initState();
    getComments();
  }

  void getComments() async {
    try {
      QuerySnapshot snap = await FirebaseFirestore.instance
          .collection('users')
          .doc(widget.snap['followers'])
          .collection('users')
          .get();
    } catch (e) {
      showSnackBar(e.toString(), context);
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        color: mobileBackgroundColor,
        child: Card(
          child: Column(children: [
            //Header
            Container(
              padding: const EdgeInsets.symmetric(
                vertical: 4,
                horizontal: 16,
              ).copyWith(right: 0),
              child: Row(
                children: [
                  CircleAvatar(
                    radius: 16,
                    backgroundImage: NetworkImage(
                      widget.snap['photoUrl'],
                    ),
                  ),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.only(left: 8),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            widget.snap['username'],
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            )
          ]),
        ));
  }
}
  • Related