'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 1:[1]
Abir Ahsan try this, call(use) your function like this : fetchBooks(client).asStream()...
Solution 2:[2]
If you're intend to get steam with your builder function is called. You will need to declare a StreamController, it creates a simple stream that can be listened to and you basically push streams of events to the stream, using the sink. A simple snippet can help in terms of displaying a ticking crypto price every 3 seconds:
StreamController<DataModel> _streamController = StreamController();
@override
void dispose() {
// stop streaming when app close
_streamController.close();
}
@override
void initState() {
// TODO: implement initState
super.initState();
// A Timer method that run every 3 seconds
Timer.periodic(Duration(seconds: 3), (timer) {
getCryptoPrice();
});
}
// a future method that fetch data from API
Future<void> getCryptoPrice() async{
var url = Uri.parse('https://api.nomics.com/v1/currencies/ticker?key=your_api_key&ids=DOGE');
final response = await http.get(url);
final databody = json.decode(response.body).first;
DataModel dataModel = new DataModel.fromJson(databody);
// add API response to stream controller sink
_streamController.sink.add(dataModel);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: StreamBuilder<DataModel>(
stream: _streamController.stream,
builder: (context,snapdata){
switch(snapdata.connectionState){
case ConnectionState.waiting: return Center(child: CircularProgressIndicator(),);
default: if(snapdata.hasError){
return Text('Please Wait....');
}else{
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('${dataModel.name}',style: TextStyle(fontSize: 25),),
SizedBox(height: 20,),
SvgPicture.network('${dataModel.image}',width: 150,height: 150,),
SizedBox(height: 20,),
Text('\$${dataModel.price}',style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold),)
],
),
);
}
}
},
),
),
);
}
More about the code here: https://protocoderspoint.com/flutter-dart-stream-basic-example-fetch-crypto-currency-api-data/ You can Learn more: using these references
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jhakiz |
Solution 2 | Xcode |