简体   繁体   English

Flutte - JSON 反序列化数据提取到 FutureBuilder 返回 null 值

[英]Flutte - JSON deserialized data fetched to FutureBuilder return null value

I'm trying to return ListView of photos via FutureBuilder fetched with data from API.我正在尝试通过从 API 获取的数据通过 FutureBuilder 返回照片的 ListView。 While values are added to List in my service and assigned properly, values fetched to List Builder are null.在我的服务中将值添加到 List 并正确分配时,获取到 List Builder 的值是 null。 I don't know why calling service method to return Future<List> returns list of null.我不知道为什么调用服务方法返回 Future<List> 会返回 null 的列表。

My model:我的 model:

class Photo {
  String id;
  String photoDesc;
  String photoAuthor;
  String photoUrlSmall;
  String photoUrlFull;
  String downloadUrl;
  int likes;

  Photo(
      {this.id,
      this.photoDesc,
      this.photoAuthor,
      this.photoUrlSmall,
      this.photoUrlFull,
      this.downloadUrl,
      this.likes});

  Photo.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    photoDesc = json['description'] != null
        ? json['description']
        : json['alt_description'];
    photoAuthor = json['user']['name'] != null
        ? json['user']['name']
        : json['user']['username'];
    photoUrlSmall = json['urls']['small'];
    photoUrlFull = json['urls']['full'];
    downloadUrl = json['links']['download'];
    likes = json['likes'];
  }
}

My service:我的服务:

Future<List<Photo>> getRandomData1() async {
    List<Photo> randomPhotos;
    _response = await http.get(Uri.parse(
        '$unsplashUrl/photos/random/?client_id=${_key.accessKey}&count=30'));
    if (_response.statusCode == 200) {
      return randomPhotos = (json.decode(_response.body) as List).map((i) {
        Photo.fromJson(i); 
        print(Photo.fromJson(i).id); // **i.e. printing returns proper values**
          }).toList();
        } else {
          print(_response.statusCode);
          throw 'Problem with the get request';
        }
      }

My builder:我的建设者:

class RandomPhotosListView extends StatefulWidget {
  @override
  _RandomPhotosListViewState createState() => _RandomPhotosListViewState();
}

class _RandomPhotosListViewState extends State<RandomPhotosListView> {
  final UnsplashApiClient unsplashApiClient = UnsplashApiClient();
  Future _data;

  ListView _randomPhotosListView(data) {
    return ListView.builder(
        itemCount: data.length,
        itemBuilder: (context, index) {
          return Text("${data[index]}"); 
        });
  }

  @override
  void initState() {
    super.initState();
    _data = unsplashApiClient.getRandomData1();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _data,
      builder: (context, snapshot) {
        print(snapshot.data);          // i.e. snapshot.data here is list of nulls
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(child: CircularProgressIndicator());
        } else if (snapshot.hasError) {
          print(snapshot.error);
          return Text("error: ${snapshot.error}");
        } else if (snapshot.hasData) {
          return _randomPhotosListView(snapshot.data);
        }
        return Center(child: CircularProgressIndicator());
      },
    );
  }
}

The reason you are having this issue is because you need to return the parsed object in your mapping function.您遇到此问题的原因是您需要在映射 function 中返回解析的 object。

Solution #1 - add the return keyword to your existing code解决方案 #1 - 将return关键字添加到现有代码中

return randomPhotos = (json.decode(_response.body) as List).map((i) {
 return Photo.fromJson(i); // <-- added return keyword here
}).toList();

Solution #2 - Use Arrow to define the return解决方案 #2 - 使用箭头定义回报

This solution suits your code since you aren't manipulating the Photo object or any other data within the mapping.此解决方案适合您的代码,因为您没有操作照片 object 或映射中的任何其他数据。

return randomPhotos = (json.decode(_response.body) as List).map((i) => Photo.fromJson(i)).toList();

Either solution should work.任何一种解决方案都应该有效。 Choose what suits your coding style and your needs.选择适合您的编码风格和需求的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM