I have docs in my collection, there are 2 fields. (String notes, Int date),
Date type is int because it sent like this : DateTime.now().microsecondsSinceEpoch
I want to group items using time, Like the below picture
Before this, I used ListView.Builder to list the items. It worked without problem.(Below code)
StreamBuilder(
stream: _FirebaseDB,
builder: ((context, AsyncSnapshot snapshot) {
return snapshot.hasData
? ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context, index) {
return Text(
snapshot.data.docs[index]["note"],
);
},
),
: Container();
}),
);
I wanted to group items. So I used, grouped_list: ^5.1.2
package and changed code like this,
StreamBuilder(
stream: _FirebaseDB,
builder: ((context, AsyncSnapshot snapshot) {
return snapshot.hasData
? Container(
padding: const EdgeInsets.symmetric(vertical: 5),
child: GroupedListView(
elements: [snapshot.data.docs],
groupBy: snapshot.data.docs["time"],
groupHeaderBuilder: (element) => Text("Group"),
itemBuilder: (context, element) {
return Card(
elevation: 8,
child: Text(snapshot.data.docs["note"]),
);
},
)
)
: Container();
}),
);
Its not working. It showing error like this :
type 'String' is not a subtype of type 'int' of 'index'
The following _TypeError was thrown building StreamBuilder<QuerySnapshot<Map<String,
dynamic>>>(dirty, state: _StreamBuilderBaseState<QuerySnapshot<Map<String,
dynamic>>, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>>>#63cd8):
CodePudding user response:
Solved it with this,
StreamBuilder(
stream: _FirebaseDB,
builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
if (!streamSnapshot.hasData) return const Text("Loading...");
return GroupedListView<dynamic, String>(
elements: streamSnapshot.data!.docs,
groupBy: (element) =>
element['time'],
groupSeparatorBuilder: (String value) => Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
value,
textAlign: TextAlign.center,
style:
const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
useStickyGroupSeparators: true,
floatingHeader: true,
order: GroupedListOrder.ASC,
itemBuilder: (context, dynamic element) {
return Card(
margin: const EdgeInsets.all(5),
child: ListTile(
title: Text(element['note']),
),
);
},
);
});