Flutter Listview按字母顺序排序



我想做的似乎很容易,但我不知道如何做到。数据通过我的listview中的API。我想做的是按字母顺序对列表视图中的数据进行排序。

简单地说,我想在listview中按字母顺序对来自API的数据进行排序。

这就是我获取数据的方式:

Future<List<Word>> getWord() async {
var response =
await http.get(Uri.parse('myAPIURL'));
var _words = List<Word>();
_words = (json.decode(utf8.decode(response.bodyBytes)) as List)
.map((singleWordMap) => Word.fromJson(singleWordMap))
.toList();
return _words;
}

我在这里的初始状态:

void initState() {
super.initState();
data = getWord();
data.then(
(value) {
setState(
() {
_words.addAll(value);
_wordsForDisplay = _words;
},
);
},
);
}

我未来的建设者:

FutureBuilder<List<Word>> myFutureBuilder() {
return FutureBuilder(
future: data,
builder: (context, AsyncSnapshot<List<Word>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return myWordListView();
}
},
);
}

我的列表视图:

ListView myWordListView() {
return ListView.builder(
itemCount: _wordsForDisplay.length,
itemBuilder: (context, index) {
return Dismissible(
background: Container(
alignment: Alignment.centerRight,
padding: EdgeInsets.only(right: 20.0),
color: Colors.teal,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(12.0),
child: Text(
'share',
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold),
),
),
Icon(Icons.share_outlined, color: Colors.white),
],
),
),
secondaryBackground: Container(
alignment: Alignment.centerRight,
padding: EdgeInsets.only(right: 20.0),
color: Colors.teal,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsets.all(12.0),
child: Text(
'favorite',
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold),
),
),
Icon(Icons.favorite_rounded, color: Colors.red),
],
),
),
direction: DismissDirection.horizontal,
key: Key(index.toString()),
confirmDismiss: (direction) async {
if (direction == DismissDirection.endToStart) {
_addFavorite(
Favorites(
_wordsForDisplay[index].word,
_wordsForDisplay[index].pronunciation,
_wordsForDisplay[index].meaning,
),
);
return false;
} else {
Share.share('something');
return false;
}
},
child: ExpansionTile(
title: Text(
_wordsForDisplay[index].word,
style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16.0),
),
subtitle: Text(
_wordsForDisplay[index].pronunciation[0].toUpperCase() +
_wordsForDisplay[index].pronunciation.substring(1),
),
leading: CircleAvatar(
child: Text(_wordsForDisplay[index].word[0]),
),
children: [
Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: MediaQuery.of(context).size.width,
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 7.0, horizontal: 19.0),
child: RichText(
text: TextSpan(
style: DefaultTextStyle.of(context).style,
children: <TextSpan>[
TextSpan(
text: _wordsForDisplay[index].word + ' : ',
style: TextStyle(fontWeight: FontWeight.bold),
),
TextSpan(text: _wordsForDisplay[index].meaning),
],
),
),
),
),
],
),
],
),
],
),
);
},
);
}

我的单词模型:

// To parse this JSON data, do
//
//     final word = wordFromJson(jsonString);
import 'dart:convert';
List<Word> wordFromJson(String str) =>
List<Word>.from(json.decode(str).map((x) => Word.fromJson(x)));
String wordToJson(List<Word> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Word {
Word({
this.word,
this.pronunciation,
this.meaning,
});
String word;
String pronunciation;
String meaning;
factory Word.fromJson(Map<String, dynamic> json) => Word(
word: json["word"],
pronunciation: json["pronunciation"],
meaning: json["meaning"],
);
Map<String, dynamic> toJson() => {
"word": word,
"pronunciation": pronunciation,
"meaning": meaning,
};
}

由于它是一个列表,您可以使用sort()函数

只是,在生成器中使用列表之前先对其进行排序。

_wordsForDisplay.sort((a, b) => a.word.compareTo(b.word));

我在打电话,所以现在无法完全编写或测试代码。

最快的方法是在onState方法中通过传递Comparable来对列表进行排序:然后

_words.sort((a,b) => a.word.compareTo(word))

在我看来,如果你需要在其他地方对列表进行排序,最干净的方法是:

  1. 使Word类实现Comparable
  2. 重写compareTo方法
  3. 在onSet方法中对列表进行排序
class Word implement Comparable {
...
@override
int compareTo(Word other) => this.word.compareTo(other.word);

然后

setState(
() {
_words.addAll(value);
_words.sort();
_wordsForDisplay = _words;
},
);

最新更新