首页 > 解决方案 > 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 ?

标签: jsonflutterstreamfuture

解决方案


Abir Ahsan试试这个,像这样调用(使用)你的函数:fetchBooks(client).asStream()...


推荐阅读