Refreshing Future Builder

7,300 views
Skip to first unread message

K Wilde

unread,
Jul 24, 2018, 9:38:32 PM7/24/18
to Flutter Dev
Hi,

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();
},
),
)
);
}
}

Ralph Bergmann

unread,
Jul 25, 2018, 4:44:58 AM7/25/18
to flutt...@googlegroups.com
I think the best way to do that is to use a StreamBuilder in combination
with a BLoC. Your update method can fill the BLoC which will
automatically update the StreamBuilder.

I'm not sure, but I guess a FutureBuilder is for one update only and not
for continually updates.

You can see more about BLoC in this video:
https://www.youtube.com/watch?v=RS36gBEp8OI


Ralph



Am 25.07.18 um 03:38 schrieb K Wilde:
> --
> You received this message because you are subscribed to the Google
> Groups "Flutter Dev" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to flutter-dev...@googlegroups.com
> <mailto:flutter-dev...@googlegroups.com>.
> For more options, visit https://groups.google.com/d/optout.


--

Ralph Bergmann


www http://www.dasralph.de | http://www.the4thFloor.eu
mail ra...@dasralph.de
skype dasralph

facebook https://www.facebook.com/dasralph
google+ https://plus.google.com/+RalphBergmann
xing https://www.xing.com/profile/Ralph_Bergmann3
linkedin https://www.linkedin.com/in/ralphbergmann
github https://github.com/the4thfloor


pgp key id 0x421F9B78
pgp fingerprint CEE3 7AE9 07BE 98DF CD5A E69C F131 4A8E 421F 9B78

signature.asc

K Wilde

unread,
Jul 25, 2018, 8:19:06 AM7/25/18
to Flutter Dev
Thanks for the reply.  I think you're right about the FutureBuilder  although I can't find where that is explicitly documented anywhere.  The reference video is quite good.  I'll have a go at Streams and BLoc.

Ralph Bergmann

unread,
Jul 25, 2018, 8:39:20 AM7/25/18
to flutt...@googlegroups.com
Am 25.07.18 um 14:19 schrieb K Wilde:
> Thanks for the reply.  I think you're right about the FutureBuilder 
> although I can't find where that is explicitly documented anywhere.  The

It's between the lines ;-)


A Future can be completed in two ways: with a value ("the future
succeeds") or with an error ("the future fails"). Users can install
callbacks for each case.
https://docs.flutter.io/flutter/dart-async/Future-class.html


Widget rebuilding is scheduled by the completion of the future, using
State.setState, but is otherwise decoupled from the timing of the future.
https://docs.flutter.io/flutter/widgets/FutureBuilder-class.html


In other words: The Future completes with the first value and the
FutureBuilder uses this completion signal to build its ui.


Ralph

signature.asc

Rudi Floren

unread,
Jul 25, 2018, 9:00:52 AM7/25/18
to Ralph Bergmann, flutt...@googlegroups.com
You can call setState to inform the stateful widget to redraw. And save the futures to a local variable in the State which you update during the update function.

Like

Future<> item = fetchPost()


And then use this local variable for the future attribute of the widget.

When you use
_doUpdate(Timer t){
setState({
item = fetchPost();
});
}
 
your widget should update.

Sry for the layout. Using my mobile right now.

Rudi


--
You received this message because you are subscribed to the Google Groups "Flutter Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev...@googlegroups.com.

Mantas Liutkevičius

unread,
Dec 13, 2018, 6:45:31 AM12/13/18
to Flutter Dev
This works, however, if you have a loader in your future builder it only works the first time, but does not appear on subsequent executions.
Reply all
Reply to author
Forward
0 new messages