如何使用GridView --Flutter放置来自服务器的JSON数据 [英] How to put JSON data from server with GridView --Flutter

查看:70
本文介绍了如何使用GridView --Flutter放置来自服务器的JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经参考了食谱.

https://flutter.dev/docs/cookbook/networking/fetch-data

示例代码是获取单个JSON数据.

我正在尝试从StatefulWidget获取多个JSON数据. 我想通过GridView在每个网格中显示季节数据.

[
  {"id":1,"season_end":"1999/01","season_name":"First","season_start":"1999/08"}, 
  {"id":2,"season_end":"1999/07","season_name":"Second","season_start":"1999/02"}, 
  {"id":3,"season_end":"2000/01","season_name":"Third","season_start":"1999/08"}, 
  {"id":4,"season_end":"2000/07","season_name":"Forth","season_start":"2000/02"}
]

但是我不知道如何编写如下所示的更好的代码.

class _HomePageState extends State<HomePage> {
  Future<List<Season>> seasons;

  @override
  void initState(){
    super.initState();
    seasons = fetchSeasons();
  }

  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            ...
          ),
          itemBuilder: (context, index){
            return seasons[index].toString();
          }
      )
    )
  }
}

我应该使用FutureBuilder<List<Season>>,但是我不知道如何与GridView一起使用. 您有什么建议吗?拜托.

Future<List<Season>> fetchSeasons() async {
  final response =
  await http.get('http://10.0.2.2:4000/api/seasons');

  if(response.statusCode == 200){
    Iterable list = json.decode(response.body);
    var seasons = list.map((season) => Season.fromJson(season)).toList();
    return seasons;
  }else{
    print('Error!!');
    throw Exception('Failed to Load Post');
  }
}

class Season {
  final int id;
  final String season_name;
  final String season_start;
  final String season_end;

  Season({this.id, this.season_name, this.season_start, this.season_end});

  factory Season.fromJson(Map<String, dynamic> json){
    return Season(
      id: json['id'],
      season_name: json['season_name'],
      season_start: json['season_start'],
      season_end: json['season_end']
    );
  }
}

解决方案

问题是seasonsFuture,而不是List,这就是为什么不能像列表一样使用它.

如果要访问该Future的列表,则需要使用FutureBuilder,如下所示:

Widget build(BuildContext context) {
  return Scaffold(
    body: FutureBuilder<List<Season>>(
      future: seasons,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return GridView.builder(
              itemCount: snapshot.data.length,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              ...
              ),
              itemBuilder: (context, index) {
                return Text("${snapshot.data[index].season_name}");
              }
          );
        } else if (snapshot.hasError) {
          return Text("Error");
        }
        return Text("Loading...");
      },
    ),
  );
}

I had referred to the cookbook.

https://flutter.dev/docs/cookbook/networking/fetch-data

The sample code is to get single JSON data.

I'm trying to get following multiple JSON data from StatefulWidget. And I would like to show season data in each grid by GridView.

[
  {"id":1,"season_end":"1999/01","season_name":"First","season_start":"1999/08"}, 
  {"id":2,"season_end":"1999/07","season_name":"Second","season_start":"1999/02"}, 
  {"id":3,"season_end":"2000/01","season_name":"Third","season_start":"1999/08"}, 
  {"id":4,"season_end":"2000/07","season_name":"Forth","season_start":"2000/02"}
]

However I have no idea to write better code like below.

class _HomePageState extends State<HomePage> {
  Future<List<Season>> seasons;

  @override
  void initState(){
    super.initState();
    seasons = fetchSeasons();
  }

  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            ...
          ),
          itemBuilder: (context, index){
            return seasons[index].toString();
          }
      )
    )
  }
}

I should have used FutureBuilder<List<Season>>, But I don't know how to use with GridView. Do you have any advice? Please.

Future<List<Season>> fetchSeasons() async {
  final response =
  await http.get('http://10.0.2.2:4000/api/seasons');

  if(response.statusCode == 200){
    Iterable list = json.decode(response.body);
    var seasons = list.map((season) => Season.fromJson(season)).toList();
    return seasons;
  }else{
    print('Error!!');
    throw Exception('Failed to Load Post');
  }
}

class Season {
  final int id;
  final String season_name;
  final String season_start;
  final String season_end;

  Season({this.id, this.season_name, this.season_start, this.season_end});

  factory Season.fromJson(Map<String, dynamic> json){
    return Season(
      id: json['id'],
      season_name: json['season_name'],
      season_start: json['season_start'],
      season_end: json['season_end']
    );
  }
}

解决方案

The problem is that seasons is a Future, not a List, that's why you can't use it like a list.

If you want to access the list of that Future, you need to use FutureBuilder, like this:

Widget build(BuildContext context) {
  return Scaffold(
    body: FutureBuilder<List<Season>>(
      future: seasons,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return GridView.builder(
              itemCount: snapshot.data.length,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              ...
              ),
              itemBuilder: (context, index) {
                return Text("${snapshot.data[index].season_name}");
              }
          );
        } else if (snapshot.hasError) {
          return Text("Error");
        }
        return Text("Loading...");
      },
    ),
  );
}

这篇关于如何使用GridView --Flutter放置来自服务器的JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆