[Flutter] Firestoreからデータを取り出し名前をアルファベット順にsortした時に詰まったところ

FirestoreにはXxxStateクラスをJsonに変換したものを入れている。

XxxListStateProviderクラスの中にgetXxxList()という関数があり、これが呼ばれると、以下のgetDocs(collection, id)が実行されListを取得できる。このListの中に入っているQueryDocumentSnapshotはそのままではデータにアクセスできない。データにアクセスするには.data()をつける必要がある(*1)

Future getDocs(collection, id) async {
   List<QueryDocumentSnapshot> qds = [];
   try {
     QuerySnapshot qs =
         await FirebaseFirestore.instance.collection(collection).get();
     qs.docs.forEach((doc) {
       if (id == doc["ownerId"]) qds.add(doc);
     });
   } catch (e) {
     throw (e);
   }
   return qds;
 }

次の詰まりポイントは、JsonからXxxStateクラスへ変換

_list = _list.map((e) => XxxState.fromJson(e)).toList();

最後の詰まりポイントは、toString()

_list.sort((a, b) => a.name.toString().compareTo(b.name.toString()));

toString()を付けないと以下のようなエラーが出てしまう。

Unhandled Exception: NoSuchMethodError: Class 'String' has no instance method '<'.


import 'package:flutter/material.dart';
import 'package:hooks_riverpod/all.dart';
import 'package:xxx/client/firestore.dart';
import 'package:xxx/entity/xxx.dart';
import 'package:xxx/entity/xxx_list.dart';
import 'package:xxx/provider/login_provider.dart';
import 'package:state_notifier/state_notifier.dart';

final xxxListStateProvider =
   StateNotifierProvider((_) => XxxListStateProvider());
   
class XxxListStateProvider extends StateNotifier<XxxListState> {
 XxxListStateProvider() : super(const XxxListState());
 Reader read;
 Future initState(reader) async {
   read = reader;
 }
 void dispose() {}
 
 void getXxxList() async {
   var _list = await read(fireStoreProvider)
       .getDocs('xxxs', read(loginStateProvider).state.uid);
   //       // snapshotからデータを取り出す(*1)
   _list = _list.map((e) => e.data()).toList();
   //
   // jsonからXxxStateクラスへ変換(*2)
   _list = _list.map((e) => XxxState.fromJson(e)).toList();
   state = state.copyWith(list: _list);
 }
 
 void addWidgetList(list) {
   var resultList = List<Widget>();
   list.forEach((val) {
     resultList.add(Row(
       children: [
         Text(val.name),
       ],
     ));
   });
   state = state.copyWith(displayList: resultList);
 }
 
 void sortList(list) {
   final _list = list;
   if (_list != null) {
     // _list.forEach((e) => print(e.name));
     _list.sort((a, b) => a.name.toString().compareTo(b.name.toString()));
     // _list.forEach((e) => print(e.name));
     state = state.copyWith(list: _list);
   }
 }
}


この記事が気に入ったらサポートをしてみませんか?