json - Flutter:将未来转换为流
问题描述
我从我的 json API 获取数据作为 Future 。并使用我的 Flutter Mobile 应用程序。
这是我从 API 获取数据的代码-
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
Future<List<Book>> fetchBooks(http.Client client) async {
final response =
await client.get('json URL');
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parseBooks, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Book> parseBooks(String responseBody) {
final parsed = jsonDecode(responseBody).cast<String, dynamic>();
return parsed['data'].map<Book>((json) => Book.fromJson(json)).toList();
}
class Book {
final String name;
final String author;
final String genreClass;
final String pdf;
final int category;
Book({
this.name,
this.author,
this.genreClass,
this.pdf,
this.category,
});
factory Book.fromJson(Map<String, dynamic> json) {
return Book(
name: json['name'] as String,
pdf: json['pdf'] as String,
author: json['author'] as String,
genreClass: json['genre_class'] as String,
category: json['category'] as int,
);
}
}
但我想把它作为 Stream 。请有人帮助我,我怎样才能将我的代码从 Future 转换为 Stream ?
解决方案
Abir Ahsan试试这个,像这样调用(使用)你的函数:fetchBooks(client).asStream()...
推荐阅读
- ios - App.Delegate 从 ViewController 到 TabController Swift 5
- google-cloud-firestore - Firebase 使用侦听器与完整查询
- ssas - 来自 ssas 多维立方体,如何通过 salesPoint 和 month 从 factsales 中获得最高销售额
- node.js - 我如何编写一个从 mongodb 查询的辅助函数,然后可以为任何 ejs 模板调用此函数
- responsive - 我怎样才能使网站移动友好?
- java - 在java中使用递归来反转字符串
- python - 使用 SymPy 解决具有符号数量变量的约束优化问题
- git - git push a detached head to a dev branch of remote
- php - 没有点运算符的字符串中的 PHP 函数
- node.js - 在mongodb nodejs中从具有字符串/ id数组的文档中查找数据