在Flatter中获取|加载json数据到列表是如何工作的?

在Flatter中获取|加载json数据到列表是如何工作的?,json,flutter,dart,async-await,Json,Flutter,Dart,Async Await,在我下面的例子中,它是如何工作的 我试了很多方法,但就是想不出来 另外,如何加载本地json文件并将其键:值作为类使用 class Countries{ int id; String name; Countries(this.id,this.name); static Future<List<Countries>> getJsonCountries() async { String apiUrl = "https://gist.githubus

在我下面的例子中,它是如何工作的

我试了很多方法,但就是想不出来

另外,如何加载本地json文件并将其键:值作为类使用

class Countries{
  int id;
  String name;

  Countries(this.id,this.name);

  static Future<List<Countries>> getJsonCountries() async {
    String apiUrl = "https://gist.githubusercontent.com/keeguon/2310008/raw/bdc2ce1c1e3f28f9cab5b4393c7549f38361be4e/countries.json";
    http.Response resp = await http.get(apiUrl);
    return json.decode(resp.body);
  }

  static List<Countries> getCountries() {

        List<Countries> ls =  getJsonCountries() as List<Countries>; // Idk why this does not work ..
        return ls;
        // return <Countries>[ <-- this works fine ...
        //   Countries(1,'Morocco'),
        //   Countries(2,'France'),
        //   Countries(3,'USA'),
        //   Countries(4,'Tunisia'),
        // ];
  }
}

您的json文件格式不正确。字符串应该用双引号括起来。这将立即阻止您在Dart/flatter中解析json。值和键都需要在双引号中才能由Dart解析

您可以通过在此处复制粘贴json并进行测试来检查: