我想從更短的距離到更遠的距離對串列進行排序,但我計算了串列內的公里數,并且資料來自 Future builder,所以我不確定我是否可以訂購此串列。
這是代碼
Widget build(BuildContext context) { final UserProvider userProvider = Provider.of(context);
return Scaffold(
appBar: null,
body: FutureBuilder(
future: FirebaseFirestore.instance
.collection('users')
.where('uid', isNotEqualTo: userProvider.getUser.uid)
.get(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
}
return ListView.separated(
itemCount: (snapshot.data! as dynamic).docs.length,
padding: const EdgeInsets.only(top: 30),
separatorBuilder: (BuildContext context, int index) {
return const Divider(
color: Colors.grey,
);
},
itemBuilder: (context, index) {
String _titleName = (snapshot.data! as dynamic).docs[index]
['name']
' '
(snapshot.data! as dynamic).docs[index]['lastName'];
return ListTile(
title: Text(
_titleName,
style: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 18),
),
subtitle: Column(children: <Widget>[
Row(children: [
Text(_subtitle,
style: const TextStyle(fontWeight: FontWeight.bold))
]),
Row(children: [
Text('From'
(snapshot.data! as dynamic).docs[index]['location']
['nameL']
' distance'),
Text(Haversine.distance(
userProvider.getUser.location.latitude,
userProvider.getUser.location.longitude,
(snapshot.data! as dynamic).docs[index]
['location']['latitude'],
(snapshot.data! as dynamic).docs[index]
['location']['longitude'])
' km')
])
]),
onTap() {}
);
},
);
},
));
}
uj5u.com熱心網友回復:
與其直接從 Firestore 中提取資料并放入 FutureBuilder,不如將這個功能移動到您提供的服務UserProvider中,例如(或其他服務),這樣您就可以封裝資料獲取邏輯和排序邏輯在那里,像這樣:
class UserProvider {
Future<User> getUserData() {
List<User> orderedUsers = [];
QuerySnapshot<Map<String, dynamic>> usersSnapshot = await
FirebaseFirestore.instance
.collection('users')
.where('uid', isNotEqualTo: userProvider.getUser.uid)
.get();
// perform your ordering logic here
// using the Haversine.distance
// then populate the orderedUsers collection,
// and return it
return orderedUsers;
}
然后在您的 FutureBuilder 中,只需執行以下操作:
FutureBuilder(
future: userProvider.getData(),
builder: (context, snapshot) {
// the rest of your rendering logic
}
)
將您的 Firebase 資料獲取封裝在提供的服務中是一種很好的做法,這樣您就可以將其與 UI 呈現邏輯分離。只是一個想法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/426601.html
