Flutter按状态对JSON进行排序

时间:2018-09-14 04:16:23

标签: dart flutter

我正在尝试按键(状态(帐单))对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。如果我在没有排序部分的情况下正常进行操作,那就很好了。

还有其他可以实现的方法或修补程序吗?

1 个答案:

答案 0 :(得分:0)

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

我不确定您在哪里尝试对哪个列表进行排序,但是如果您编写something.sort(compareFunction),则它将对列表进行排序并得出null。 尝试改写something..sort(compareFunction)。这将对列表进行排序,但表达式将求值到列表,而不是调用sort的结果。

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