【问题标题】:Flutter Sorting JSON by StatesFlutter 按状态对 JSON 进行排序
【发布时间】:2018-09-14 04:16:22
【问题描述】:

我正在尝试通过键(States (Billing))对我的 Json 进行排序。

这是 json。

accounts.json

{
  "Accounts": [
    {
      "Name": "Klinik Pakar Mata & Surgeri Tg.Kamal",
      "TPA Customer ID": "9708",
      "Organization Type": "Clinic",
      "Organization Subtype": "GP",
      "Street (Billing)": "22-1, Jalan Tanjong Laboh, Kampung Bahagia, 83000 Batu Pahat, Johor, Malaysia",
      "City (Billing)": "batu pahat",
      "State (Billing)": "Johor",
      "Coordinate" : {
        "Latitude" : "1.846280",
        "Longitude" : "102.938568"
      }
    },
    {
      "Name": "KLINIK RS SHIVA SDN.BHD",
      "TPA Customer ID": "740",
      "Organization Type": "Clinic",
      "Organization Subtype": "GP",
      "Street (Billing)": "No 3, Medan 23, Bandar Baru Salak Tinggi",
      "City (Billing)": "Sepang",
      "Postal Code (Billing)": "43900",
      "State (Billing)": "Selangor",
      "Country (Billing)": "Malaysia",
      "Coordinate" : {
        "Latitude" : "1.846280",
        "Longitude" : "102.938568"
      }
    }
  ]
}

这是json文件的模型类

accounts_model.dart

class Accounts{

  List<AccountInfo> accountinfo;

  Accounts({this.accountinfo});

  factory Accounts.fromJson(Map<String, dynamic> json){

    var accJson = json["Accounts"] as List;
    List<AccountInfo> accList = accJson.map((i) => AccountInfo.fromJson(i)).toList();

    return Accounts(
      accountinfo: accList
    );
  }
}

class AccountInfo{

  String name;
  String id;
  String orgtype;
  String subtype;
  String street;
  String city;
  String country;
  Coordinates coordinates;

  AccountInfo({this.name, this.id, this.orgtype, this.subtype, this.street, this.city, this.country, this.coordinates});

  factory AccountInfo.fromJson(Map<String, dynamic> json){

    return AccountInfo(
      name: json["Name"],
      id: json["TPA Customer ID"],
      orgtype: json["Organization Type"],
      subtype: json["Organization Subtype"],
      street: json["Street (Billing)"],
      city: json["City (Billing)"],
      country: json["State (Billing)"],
      coordinates: Coordinates.fromJson(json["Coordinate"])
    );
  }
}

class Coordinates{

  String lat;
  String lng;

  Coordinates({this.lat, this.lng});

  factory Coordinates.fromJson(Map<String, dynamic> json){

    return Coordinates(
      lat: json["Latitude"],
      lng: json["Longitude"]
    );
  }
}

这是包含帐户列表的 dart 文件

list.dart

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
import 'package:emas_app/model/accounts_model.dart';

Future<String> _loadAsset2() async{
  return await rootBundle.loadString('Assets/accounts.json');
}

//Working future for accounts
Future<Accounts> loadAccounts() async{

  final response = await _loadAsset2();
  final jsonResponse = json.decode(response);

  if(jsonResponse["State (Billing)"] == "Johor") {
    Accounts accounts = new Accounts.fromJson(jsonResponse);
    return accounts;
  }
}

class ProviderList extends StatefulWidget {

  @override
  ListState createState() {
    return new ListState();
  }
}

class ListState extends State<ProviderList> {

  @override
  Widget build(BuildContext context) {

    List<Widget> widgets = [];

    widgets.add(new ExpansionTile(
        title: new Text("Johor"),
        children: <Widget>[
          new FutureBuilder<Accounts>(
              future: loadAccounts(),
              builder: (context, snapshot){
                if(snapshot.hasData){

                  return new ListView.builder(
                      shrinkWrap: true,
                      itemCount: snapshot.data.accountinfo.length,
                      itemBuilder: (context, index){

                        String username = snapshot.data.accountinfo[index].name;
                        String address = snapshot.data.accountinfo[index].street;
                        String lat = snapshot.data.accountinfo[index].coordinates.lat;
                        String lng = snapshot.data.accountinfo[index].coordinates.lng;

                        return new ListTile(
                            title: new Text(username),
                            trailing: new Row(
                              mainAxisSize: MainAxisSize.min,
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: <Widget>[
                                new IconButton(
                                    icon: Icon(Icons.info),
                                    onPressed: null
                                ),
                                new IconButton(
                                    icon: Icon(Icons.directions),
                                    onPressed: null
                                )
                              ],
                            )
                        );
                      });
                }else{
                  return new Center(
                    child: new CircularProgressIndicator(),
                  );
                }
              })
        ]));

    return new Scaffold(
      appBar: new AppBar(title: new Text("Providers")),
      body: new Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: widgets,
      )
    );
  }
}

这是我遇到的错误

I/flutter ( 6385): The following assertion was thrown building FutureBuilder<Accounts>(dirty, state:
I/flutter ( 6385): _FutureBuilderState<Accounts>#a326f):
I/flutter ( 6385): A build function returned null.

我正在尝试查看是否可以在 Future 方法中按状态(计费)对 JSON 进行排序,但它返回 null。如果我在没有排序部分的情况下正常执行它,它就可以正常工作。

我可以实施其他方法或修复方法吗?

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    List.sort 对列表本身进行排序并且不返回任何内容(void),这就是问题的原因。您可以像这样将排序应用于 accountInfo,它应该可以工作

    if(jsonResponse["State (Billing)"] == "Johor") {
        Accounts accounts = new Accounts.fromJson(jsonResponse);
        accounts.accountinfo.sort((a, b) {
          return a.country.toLowerCase().compareTo(b.country.toLowerCase());
        });
        return accounts;
      }  
    

    或者,你可以在这里做

    factory Accounts.fromJson(Map<String, dynamic> json){
      var accJson = json["Accounts"] as List;
      List<AccountInfo> accList = accJson.map((i) => 
      AccountInfo.fromJson(i)).toList();
      accList.sort((a, b) {
          return a.country.toLowerCase().compareTo(b.country.toLowerCase());
        });
      return Accounts(
        accountinfo: accList
      );
    }
    

    【讨论】:

    • 我尝试了您建议的方式,但由于某种原因它似乎不起作用。也许我做得不好。会再试一次。
    • 是的,@mezoni,你是对的。量刑是错误的,但答案是正确的
    【解决方案2】:

    List.sort 方法总是返回 null。这是一个void 函数,所以如果你看到它的值,你就会以某种方式回避关于使用void 表达式的值的警告,可能是因为你的代码此时键入为dynamic

    我不确定您尝试对哪个列表进行排序,但如果您编写something.sort(compareFunction),那么它会对列表进行排序并计算为null。 尝试改写something..sort(compareFunction)。这将对列表进行排序,但表达式评估为列表,而不是调用 sort 的结果。

    sort 函数修改列表。如果您希望在多个地方使用同一个列表,您可能不希望每个地方都以自己的方式对列表进行排序,而应该在排序之前制作一份副本:something.toList()..sort(compareFunction)

    【讨论】:

      猜你喜欢
      • 2018-12-07
      • 2021-03-30
      • 2010-10-27
      • 2019-06-06
      • 2019-11-22
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      相关资源
      最近更新 更多