按字母顺序对JSON进行排序-Flutter

时间:2018-06-28 13:59:30

标签: json dart flutter

我希望能够按字母顺序将profileList返回到ListView。

我有我的“所有人”类,该类具有一个使用json并创建人员列表的ListView小部件。

下面的代码来自我正在读取json的All People类。

class AllPeople extends StatefulWidget {
final String title;

AllPeople(this.title);

@override
AllPeopleState createState() => AllPeopleState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
  title: Text("Listviews"),
),
);
}

class AllPeopleState extends State<AllPeople> {
 List data;
 List<Profile> profiles;

 Future<String> getData() async {
 var response = await http.get(
    Uri.encodeFull("http://test.mallcomm.co.uk/json_feeds/users.json"),
    headers: {"Accept": "application/json"});

  fetchPeople().then((List<Profile> p) {
    this.setState(() {
    data = json.decode(response.body);
    profiles = p;
  });
});

return "Success!";
}

@override
void initState() {
  this.getData();
}

 @override
 Widget build(BuildContext context) {
  return Scaffold(
  appBar: AppBar(
    title: Text('CMS Users'),
  ),
  body: ListView.builder(
      padding: EdgeInsets.only(top: 20.0, left: 4.0),
      itemExtent: 70.0,
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (BuildContext context, int index) {
        return Card(
          elevation: 10.0,
          child: InkWell(
            onTap: () {
              Navigator.push(
                  context,
                  new MaterialPageRoute(
                    builder: (BuildContext context) =>
                        new PeopleDetails("Profile Page", profiles[index]),
                  ));
            },
            child: ListTile(
              leading: CircleAvatar(
                child: Text(profiles[index].getInitials()),
                backgroundColor: Colors.deepPurple,
                radius: 30.0,
              ),
              title: Text(
                  data[index]["firstname"] + "." + data[index]["lastname"]),
              subtitle: Text(
                  data[index]["email"] + "\n" + data[index]["phonenumber"]),
            ),
          ),
        );
      }),
  );
  }
 }

Future<List<Profile>> fetchPeople() async {
 try {
 http.Response response =
    await http.get('http://test.mallcomm.co.uk/json_feeds/users.json');

 List<dynamic> responseJson = json.decode(response.body);

 List<Profile> profileList =
    responseJson.map((d) => new Profile.fromJson(d)).toList();

profileList.sort((a, b) {
  return a.lastName.toLowerCase().compareTo(b.lastName.toLowerCase());
});

  return profileList;
} catch (e) {
print(e.toString());
}
return null;
}

然后我有一个“用户个人资料”类,用于存储我的json个人资料

class Profile {
 final String firstName;
 final String lastName;
 final String phoneNumber;
 final String userEmail;

bool verifiedValue = false;
bool approvedValue = false;
bool securityApprovedValue = false;
bool blockedValue = false;

Profile({this.firstName, this.lastName, this.phoneNumber, this.userEmail});

factory Profile.fromJson(Map<String, dynamic> json) {
  return new Profile(
  firstName: json["firstname"],
  lastName: json["lastname"],
  phoneNumber: json["phonenumber"],
  userEmail: json["email"],
  );
 }

我试图做类似

 profileList.sort((a,b) {
return a.lastName.toLowerCase().compareTo(b.lastName.toLowerCase());
 });

就在我返回profileList之前,但是它没有用。我尝试查看一些不同的示例,但是如果我说实话,我不太了解。

1 个答案:

答案 0 :(得分:0)

您建议的排序功能似乎确实按预期运行(但是,当然,仅比较姓氏-如果姓氏相等,则可能要比较姓氏)。我整理了一下,以产生这个工作示例:

import 'dart:convert';
import 'dart:async';

import 'package:http/http.dart' as http;

main() async {
  fetchPeople().then((list) {
    list.forEach(print);
  });
}

Future<List<Profile>> fetchPeople() async {
  try {
    http.Response response =
        await http.get('http://test.mallcomm.co.uk/json_feeds/users.json');

    List<dynamic> responseJson = json.decode(response.body);

    List<Profile> profileList =
        responseJson.map((d) => new Profile.fromJson(d)).toList();

    profileList.sort((a, b) {
      return a.lastName.toLowerCase().compareTo(b.lastName.toLowerCase());
    });

    return profileList;
  } catch (e) {
    print(e.toString());
  }
}

class Profile {
  final String firstName;
  final String lastName;
  final String phoneNumber;
  final String userEmail;

  bool verifiedValue = false;
  bool approvedValue = false;
  bool securityApprovedValue = false;
  bool blockedValue = false;

  Profile({this.firstName, this.lastName, this.phoneNumber, this.userEmail});

  factory Profile.fromJson(Map<String, dynamic> json) {
    return new Profile(
      firstName: json["firstname"],
      lastName: json["lastname"],
      phoneNumber: json["phonenumber"],
      userEmail: json["email"],
    );
  }

  @override
  String toString() {
    return 'Profile: $firstName $lastName';
  }
}

这是一个有效的State示例。

class _MyHomePageState extends State<MyHomePage> {
  List<Profile> profiles = [];

  @override
  void initState() {
    super.initState();
    _refresh();
  }

  void _refresh() {
    fetchPeople().then((list) {
      setState(() {
        profiles = list;
      });
    });
  }

  Future<List<Profile>> fetchPeople() async {
    try {
      http.Response response =
      await http.get('http://test.mallcomm.co.uk/json_feeds/users.json');

      List<dynamic> responseJson = json.decode(response.body);

      List<Profile> profileList =
      responseJson.map((d) => new Profile.fromJson(d)).toList();

      profileList.sort((a, b) {
        return a.lastName.toLowerCase().compareTo(b.lastName.toLowerCase());
      });

      return profileList;
    } catch (e) {
      print(e.toString());
      return [];
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new ListView.builder(
        itemBuilder: (context, i) => new Text('${profiles[i].firstName} ${profiles[i].lastName}'),
        itemCount: profiles.length,
      ),
    );
  }
}