I would like to render a widget that needs an HTTP call to gather some data.
Got the following code (simplified)
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'async demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var asyncWidget;
@override
initState() {
super.initState();
loadData().then((result) {
print(result);
setState(() {
asyncWidget = result;
});
});
}
loadData() async {
var widget = new AsyncWidget();
return widget.build();
}
@override
Widget build(BuildContext context) {
if(asyncWidget == null) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Loading..."),
),
);
} else {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: this.asyncWidget,
),
);
}
}
}
class MyRenderer {
MyRenderer();
Widget render (List data) {
List<Widget> renderedWidgets = new List<Widget>();
data.forEach((element) {
renderedWidgets.add(new ListTile(
title: new Text("one element"),
subtitle: new Text(element.toString()),
));
});
var lv = new ListView(
children: renderedWidgets,
);
return lv;
}
}
class MyCollector {
Future gather() async {
var response = await // do the http request here;
return response.body;
}
}
class AsyncWidget {
MyCollector collector;
MyRenderer renderer;
AsyncWidget() {
this.collector = new MyCollector();
this.renderer = new MyRenderer();
}
Widget build() {
var data = this.collector.gather();
data.then((response) {
var responseObject = JSON.decode(response);
print(response);
return this.renderer.render(responseObject);
});
data.catchError((error) {
return new Text("Oups");
});
}
}
My code works like this : the widget using async data takes a collector (which make the http call) and a renderer which will render the widgets with the http data. I create an instance of this widget on the initState() and then I make my async call.
I found some documentation saying that we should use the setState() method to update the widget with the new data but this doesn't work for me.
However when I put some logs, i see the HTTP call is done and the setState() method is called, but the widget does not update.