Home > Software engineering >  Flutter - Fetch first item from a list stored in firebase
Flutter - Fetch first item from a list stored in firebase

Time:10-21

I need to get the 1st element of a list of String that stored in Firestore Database.

I can only fetch the full list not a single item...

Here is my code.

class Unpublished extends StatelessWidget {
  const Unpublished({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    FirebaseService service = FirebaseService();

    return StreamBuilder<QuerySnapshot>(
      stream: service.products.where('approved', isEqualTo: false).snapshots(),
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return const Text('Something wrong!');
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }

        if (snapshot.data!.size == 0) {
          return const Center(
            child: Text('No products'),
          );
        }

        return SingleChildScrollView(
          child: ListView.builder(
            shrinkWrap: true,
            itemCount: snapshot.data!.size,
            itemBuilder: (context, index) {
              Map<String, dynamic> dataa =
                  snapshot.data!.docs[index].data() as Map<String, dynamic>;

              return ListTile(
                title: Text(dataa['productName']),
                subtitle: Text(snapshot.data!.docs[index]['imageUrl'].toString()),
              );
            },
          ),
        );
      },
    );
  }
}

Here by subtitle I can get the list...

i.e . subtitle: Text(snapshot.data!.docs[index]['imageUrl'].toString()),

But I need to get only the first element.

And here's an example of my list stored in firebase.

enter image description here

Please guide me to that.

CodePudding user response:

Try this:

  Map<String, dynamic> dataa =
      snapshot.data!.docs[index].data() as Map<String, dynamic>;
  var subtitles = snapshot.data!.docs[index]['imageUrl'] as List;
  var firstSubtitle = subtitles.isEmpty? '': subtitles.first;
  return ListTile(
    title: Text(dataa['productName']),
    subtitle: Text(firstSubtitle),
  );
  • Related