Search code examples
jsonflutterstreamfuture

Flutter: convert future to stream


I am getting data as Future from my json API. And use my Flutter Mobile app.

Here is my code for getting data from 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,
    );
  }
}

But I want to get it as Stream.Please someone help me, how can I convert my code from Future to Stream ?


Solution

  • Abir Ahsan try this, call(use) your function like this : fetchBooks(client).asStream()...