首页 > 解决方案 > Flutter Listview 按字母顺序排序

问题描述

我想做的事情似乎很容易,但我不知道该怎么做。数据来自我列表视图中的 API。我想要做的是按字母顺序对进入列表视图的数据进行排序。

简而言之,我想按字母顺序对列表视图中来自 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,
      };
}

标签: flutter

解决方案


由于它是一个列表,您可以使用该sort()功能

只是,在构建器中使用它之前对列表进行排序。

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


推荐阅读