Home > Blockchain >  Make a list of Flutter Firebase field
Make a list of Flutter Firebase field

Time:07-15

enter image description here

Hi, I want to make a list inside the Flutter Firebase field. I'm creating an id for followers in the Field. In Firebase, there is a collection, user ID and followers id in the field. My encodings are as follows. But I'm not making a list. What are the changes I will make?

Followers_card

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> {
  List<dynamic> followersList = []; // shouldn't use dynamic

  getdata() async {
    await FirebaseFirestore.instance
        .collection("users")
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .get()
        .then((value) async {
      // get followerIds
      List<String> follwerIds = List.from(value.data()!['followers']);
      // loop through all ids and get associated user object by userID/followerID
      for (int i = 0; i < follwerIds.length; i  ) {
        var followerId = follwerIds[i];
        var data = await FirebaseFirestore.instance
            .collection("users")
            .doc(followerId)
            .get();

        // push that data into followersList variable as we are going
        // to use that in listViewBuilder
        followersList.add(data);
      }
      setState(() {});
    });

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

  @override
  Widget build(BuildContext context) {
    // use the listView builder to render the list of followers card
    return SingleChildScrollView(
      physics: NeverScrollableScrollPhysics(),
      child: ListView.builder(
          shrinkWrap: true,
          itemCount: followersList.length,
          itemBuilder: (context, index) {
            var followerItem = followersList[index];
            print('photoUrl');

            return _buildFollowersCard(
                followerItem['photoUrl'], followerItem['username']);
          }),
    );
  }

  Widget _buildFollowersCard(String photoUrl, String username) {
    return Container(
      height: 70,
      width: double.infinity,
      color: mobileBackgroundColor,
      child: Card(
        child: Column(children: [
          //Header
          Container(
            height: 40,
            width: double.infinity,
            padding: const EdgeInsets.symmetric(
              vertical: 4,
              horizontal: 16,
            ).copyWith(right: 0),
            child: Row(
              children: [
                CircleAvatar(
                  radius: 16,
                  backgroundImage: NetworkImage(
                    photoUrl,
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.only(left: 8),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          username,
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          )
        ]),
      ),
    );
  }
}

followers_screen

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

CodePudding user response:

The problem is that _FollowersScreenState.initState is in the wrong place. It's inside the function getdata that it is trying to call. The initState is never called. That's why there is no list being built.

Also, setState is the one that assigns State values. So first, populate a temporary list of followers and then assign it to the State one inside the setState callback.

Below is the fixed snippet code for _FollowersScreenState:

class _FollowersCardState extends State<FollowersCard> {
  List<dynamic> followersList = []; // shouldn't use dynamic

  getdata() async {
    List<dynamic> followers = [];

    final currentUserSnapshot = await FirebaseFirestore.instance
        .collection('users')
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .get();

    // get followerIds
    List<String> follwerIds =
        List.from(currentUserSnapshot.data()!['followers']);
    // loop through all ids and get associated user object by userID/followerID
    for (int i = 0; i < follwerIds.length; i  ) {
      var followerId = follwerIds[i];
      var data = await FirebaseFirestore.instance
          .collection('users')
          .doc(followerId)
          .get();

      // push that data into the temp list variable as we are going
      // to use that in to setState
      followers.add(data);
    }
    setState(() => followersList = followers);
  }

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

  ...
  • Related