💹Agrupamento de mensagens

Aqui apenas vou demonstrar como fiz o uso do GroupedListView para agrupar as mensagens do chat por data e de maneira decrescente.

O widget e suas determinações ficaram da seguinte maneira:

GroupedListView<dynamic, String>(
 elements: snapshot.data!.toList(),
 controller: _scrollController,
 reverse: true,
 order: GroupedListOrder.DESC,
 groupBy: (e) => getUpdatedAtDateFormatted(e != null && e.createdAt != null &&
    e.createdAt is int ? e.createdAt : Timestamp.now().millisecondsSinceEpoch, ),
 itemComparator: (item1, item2) => (item1.createdAt != null && item1.createdAt is int)
  && (item2.createdAt != null && item2.createdAt is int) ? item1.createdAt .compareTo(item2.createdAt): 1,
 sort: false,
groupSeparatorBuilder: (String groupByValue) =>
Center(
child: Padding(
  padding: const EdgeInsets.all(10),
  child: Text(
    groupByValue.replaceAll("Z-", ""),
    style: Fonts.headline6.copyWith(
    color: CustomColors.darkerGrey,
    fontWeight: FontWeight.w600,
      ),
    ),
  ),
),

Onde a função de getUpdatedAtDateFormatted é a seguinte:

 String getUpdatedAtDateFormatted(int date) {
    DateTime currentDate = Timestamp.fromMillisecondsSinceEpoch(date).toDate();

    DateTime today = DateTime(
      DateTime.now().year,
      DateTime.now().month,
      DateTime.now().day,
      0,
      0,
      0,
    );

    DateTime yesterday = DateTime(
      DateTime.now().year,
      DateTime.now().month,
      DateTime.now().subtract(const Duration(days: 1)).day,
      0,
      0,
      0,
    );

    if (currentDate.isBefore(today) && currentDate.isAfter(yesterday)) {
      return "Ontem";
    } else if (currentDate.isBefore(today) && !currentDate.isAfter(yesterday)) {
      return DateFormat.yMMMd('pt_Br').format(currentDate);
    } else if (currentDate.isAfter(today)) {
      return "Z-Hoje";
    }

    return "";
  }

Com isso, as mensagen ficam ordenadas da mais atual para as mais antigas, e agrupadas por "Hoje", "Ontem" ou a data em que foram enviadas.

Last updated