import 'dart:async';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:dio/dio.dart';
void main()=>runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage()
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
StreamController _streamController;
StreamSubscription _streamSubscription;
StreamSink _streamSink;
@override
void dispose() {
// TODO: implement dispose
_streamController.close();
super.dispose();
}
@override
void initState() {
// TODO: implement initState
_streamController=StreamController.broadcast();
_streamSink=_streamController.sink;
_streamController.stream.listen(onData,onError:onError,onDone: onDone);
super.initState();
}
onData(value){
print(value);
}
onError(Error){Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context){}));}
onDone(){print('done');}
pauseStream(){
_streamSubscription.pause();
}
resumeStream(){
_streamSubscription.resume();
}
cancleStream(){
_streamSubscription.cancel();
}
fetchData()async{
var datas;
Response response = await Dio().get("http://jsonplaceholder.typicode.com/posts");
if(response.statusCode==200){
final _responseData=response.data;
datas=_responseData.map((item)=>User.fromJson(item));
}else{throw Exception('faild to fetch data');}
return datas;
}
addDataToStream()async{
var datas;
datas=await fetchData();
_streamSink.add(datas);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: fetchData(),
builder: (BuildContext context,AsyncSnapshot snapshot){
print('snapshot_data:${snapshot.data}');
print('connectionstate:${snapshot.connectionState}');
if(snapshot.connectionState==ConnectionState.waiting){
return Center(child: Text('loading...'),);
}
return ListView(
children: snapshot.data.map<Widget>((item){
return ListTile(
title: Text(item.title),
subtitle: Text(item.body),
leading: Icon(Icons.description),
);
}).toList(),
);
},
),
appBar: AppBar(title: Text('Rock U')),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
onPressed: (){
addDataToStream();
},
child: Icon(Icons.add),
),
);
}
}
class User {
final String title;
final String body;
final int userId;
final int id;
User(this.title, this.body,this.userId,this.id);
User.fromJson(Map<String, dynamic> json)
:title = json['title'],
id=json['id'],
userId=json['UserId'],
body = json['body'];
Map<String, dynamic> toJson() =>
<String, dynamic>{
'title': title,
'body': body,
'id':id,
'userId':userId,
};
}