繁体   English   中英

如何过滤 Flutter 中的未来列表?

[英]How to filter Future List in Flutter?

我需要过滤列表的帮助。

我在 initState 中填充列表:

  Future _organisations;

  Future<void> readJson() async {
    final String response =
        await rootBundle.loadString('assets/organisations.json');
    final data = await json.decode(response);

    List<Organization> temp = [];

    for (var item in data) {
      Organization place = Organization(
        address: item['Address'],
        contactInfo: item['Contact info'],
        organization: item['Organization'],
        phoneNumber: item['Phone number'],
        shortDescription: item['Short description'],
        subject: item['Subject'],
        tags: item['Tags'],
      );

      temp.add(place);
    }

    temp.sort((a, b) => a.organization.compareTo(b.organization));

    return temp;
  }

  @override
  void initState() {
    super.initState();
    _organisations = readJson();
  }

然后我在列表上方有一个按钮,我想用它来过滤带有 setState 的列表,但是它不起作用。 如何过滤未来类型的列表?

首先,您的方法readJson()具有Future<void>类型的返回值,这意味着您将永远无法返回List<Organization>

此外,您正在使用异步操作,这意味着您将需要使用awaitthen在某些时候获得您的价值。

以下是如何修复代码的示例:

List<Organization> _organisations;

// Simply change the return type to Future<List<Organization>>
Future<List<Organization>> readJson() async {
  final String response =
    await rootBundle.loadString('assets/organisations.json');
  final data = await json.decode(response);

  List<Organization> temp = [];

  for (var item in data) {
    Organization place = Organization(
      address: item['Address'],
      contactInfo: item['Contact info'],
      organization: item['Organization'],
      phoneNumber: item['Phone number'],
      shortDescription: item['Short description'],
      subject: item['Subject'],
      tags: item['Tags'],
    );
    temp.add(place);
  }

  /// Then you need to compare objects that are comparable.
  /// For example if you want to sort your items by their address :
  temp.sort((a, b) =>
    a.address.toLowerCase().compareTo(b.address.toLowerCase())
  );

  return temp;
}

@override
void initState() {
  super.initState();
  
  /// As you cannot use await in initState you can use then
  /// to perform an action once your asynchronous operation is
  /// done.
  ///
  /// In this case I am assigning the value to _organisations
  /// and causing a rebuild of the interface with setState.
  readJson().then((List<Organization> temp) {
    setState(() => _organisations = temp);
  });
}

Future<void>不返回任何内容。 如果您希望它返回一个列表,它应该是Future<List> 当您对列表中的项目进行排序时,您将它们与什么进行比较? item[“组织”]属于什么类型? 它必须是可比较的类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM