I'm trying to retrieve some data from a web endpoint periodically using future builder. I can get it to work initially but subsequent calls do not cause the widget to update any idea how I can go about it? Code is attached. Thanks in advance
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
//import 'comms.dart' as comms;
import 'types.dart' as userTypes;
import 'data_item.dart';
import 'data_item_detail.dart';
import 'globals.dart' as Globals;
class Post{
final int userId;
final int id;
final String title;
final List tagList;
Post({this.userId,this.id,this.title,this.tagList});
factory Post.fromJson(Map<String,dynamic> json){
return Post(
userId: json["userId"],
id: json["id"],
title: json["title"],
tagList: json["tagList"],
);
}
}
Future<Post> fetchPost() async{
String url = Uri.encodeFull(Globals.mainURL);
var response = await http.get(url,headers:{"Accept":"application.json"});
//print(response.body.toString());
//print (response.statusCode.toString());
if (response.statusCode == 200){
// response is OK
//print(Post.fromJson(json.decode(response.body)).body.toString());
return Post.fromJson(json.decode(response.body));
}else{
throw Exception("Failed to load post");
}
}
void main() {
//await getDataInitial();
runApp(new MyApp());
}
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context){
return new MaterialApp(
title: 'Mobile Data',
theme: new ThemeData(
primarySwatch: Colors.blue
),
home: new MainPage(title:"Main Window"),
routes: <String,WidgetBuilder>{
'/data_item_detail':(BuildContext context) => new DataItemDetail(),
}
);
}
}
class MainPage extends StatefulWidget{
final String title;
MainPage({Key key, this.title}) : super(key: key);
@override
_MainPageState createState() => new _MainPageState();
}
class _MainPageState extends State<MainPage> {
_doUpdate(Timer t){
fetchPost();
}
@override
Widget build(BuildContext context) {
new Timer.periodic(new Duration(seconds:10), _doUpdate);
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
backgroundColor: Colors.blue,
),
body: Center(
child: FutureBuilder<Post>(
future: fetchPost(),
builder: (context, snapshot) {
//print(snapshot.data.title);
//print (snapshot.connectionState.toString());
if (snapshot.hasData) {
//return Text('${snapshot.data}');
print("tagList " + snapshot.data.tagList.toString());
return Text(snapshot.data.tagList[0]["value"].toStringAsFixed(2));
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
),
)
);
}
}