Dart / Flutter: building widget from data obtained using async method - dart

I want to use a LietView.build populated by Widgets that obtain the data from an async method, before the widget is built. Here is my function that collects the data from a website:
fetchBasicData(String URL) async {
final response = await http.get(URL);
var document = parse(response.body);
var result = new List<dom.Node>();
result = document.getElementsByClassName('datas-nev');
var dogName = result[0].nodes[1].toString();
result = document.getElementsByClassName('datas-tipus');
var dogBreed = result[0].nodes[1].toString();
result = document.getElementsByClassName('datas-nem');
var dogGender = result[0].nodes[1].toString();
result = document.getElementsByClassName('datas-szin');
var dogColor = result[0].nodes[1].toString();
result = document.getElementsByClassName('datas-kor');
var dogAge = result[0].nodes[1].toString();
result = document.getElementsByClassName('pirobox_gall');
String imageLink;
imageLink = urlPrefix + result[0].nodes[0].attributes.values.first;
return new Dog.basic(
URL,
dogName,
dogBreed,
dogGender,
dogColor,
dogAge,
imageLink);
}
The function is executed and gathers the data, but the widget building fails with type '_Future' is not a subtype of type 'Widget' of 'child' where
Here is the function that is supposed to build the widget:
buildBasicWidget(String URL) async {
Dog myDog = await fetchBasicData(URL);
return new SizedBox(
width: 500.0,
height: 400.0,
child: new Card(
child: new Column(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
//Header image row
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Expanded(
child: new FutureBuilder(
future: fetchPortrait(myDog.imageLink),
builder: (context, snapshot) {
if (snapshot.hasData) {
return new Image.network(
snapshot.data,
fit: BoxFit.scaleDown,
);
} else {
if (snapshot.hasError) {
return new Text('Hiba');
}
}
return new Center(
child: new CircularProgressIndicator(),
);
}))
],
), //Header image row
new Row(
children: <Widget>[
new Expanded(
child: new Text(
dogName,
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18.0,
color: Colors.black),
))
],
),
new Row(
children: <Widget>[
new Expanded(
child: new Text(myDog.dogColor +
'színű, ' +
myDog.dogBreed +
' ' +
myDog.dogGender))
],
),
new Row(
children: <Widget>[
new Expanded(child: new Text('Kora: kb. ' + myDog.dogAge))
],
)
],
),
),
);
}
I tried making this function async as well, and making it wait for the fetchBasicDetails() to finish, so the data is present when it would use it.
I even tried using dynamic fetchBasicData(String URL) async {...} but that didn't help either.
Using Future<Dog> instead of dynamic also causes errors.
How could I make the buildBasicWidget use the fetchBasicData result? Or should I just handle the widget building in the fetchBasicData as a simple workaround?

You need to use a FutureBuilder and add your async function in the future argument otherwise the build method gets called before the data are obtained.
Alternatively do your async request inside initState.

Related

Dart : How to fetch data with no number id (string)?

So I was able to fetch data for 'locations' in this json using the number (0,1,2,3,4). But I was not able to fetch data from 'prayer_times' string directly. Is there any way to solve this?
I have tried Text(data["date"] because it cannot start with string right away and will give error The argument type 'dart.core::String' can't be assigned to the parameter type
'dart.core::int'.
The api is working do check the link thanks.
Data fetch display code
Card(
child: Container(
padding: EdgeInsets.all(15.0),
child: Row(
children: <Widget>[
Text("Name: "),
Text(data[0]["date"],
style: TextStyle(
fontSize: 18.0, color: Colors.black87)),
],
)),
),
API URI code
final String url = "http://api.azanpro.com/times/today.json?zone=ngs02&format=12-hour";
List data;
Future<String> getSWData() async {
var res = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
setState(() {
var resBody = json.decode(res.body);
data = resBody["prayer_times"];
});
You just need to make two changes.
Change the type of data to a Map and depending on your use case, initialise it to a default value:
Map<String, dynamic> data = {'date': "-------"};
And then get the date field directly in data
Card(
child: Container(
padding: EdgeInsets.all(15.0),
child: Row(
children: <Widget>[
Text("Name: "),
Text(data["date"],
style: TextStyle(
fontSize: 18.0, color: Colors.black87)),
],
)),
),

I want that onPressed method in IconButton return a new Container

In my flutter app, i want that when i press a IconButton, the app show the image that i click in a new container.
This is my code:
Widget build(BuildContext context) {
return Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
0 < favorites.length
? IconButton(
icon: Image.network(favorites[0]),
onPressed: (){
return new Container(
child: Column(
children: <Widget>[
Image.network(favorites[0])
],
),
);
},
)
: Container(),
]));
}
i want that image that i click show up in the black rectangle:
https://i.stack.imgur.com/YqOYa.png
The return value of onPressed is just ignored.
final VoidCallback onPressed;
returning from a callback passed around does not return the enclosing function (build()) and therefore returning the container won't have any effect.
What you rather want is something like
onPressed: () {
setState(() {isPressed = true;})
}
bool isPressed = false;
build() {
if(isPressed) {
return new Container(
child: Column(
children: <Widget>[
Image.network(favorites[0])
],
),
);
} else {
return /* as you have it in your question */
}
}
Calling setState() will cause build() to be executed again and there you can check the flat isPressed (or perhaps better name it wasPressed) and return different content this time.
You have to do something like:
List<String> favorites;
String selectedIcon;
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Row(children: favorites.map((String src) => IconButton(
icon: Image.network(src),
onPressed: (){
setState(() {
selectedIcon = src;
});
},
)).toList(),),
Container(
child: Image.network(selectedIcon),
)
],
);
}
There are no alignment, styles, decoration in this code, I think you can add what you need by yourself

Flutter: Future Builder fetch multiple data

I am consulting the news section of my website.
I'm using Future Builder to get the data from the web.
The problem I get is related to the image that I try to show on the screen.
And when there is a lot of news, the data load takes a long time and I do not know if there is a solution for loading faster.
I am consulting the text of the news through a json.
At that moment you get the URL of another JSON where the image is in thumbnail format.
I hope to solve this problem, I appreciate any help.
News.dart - Code
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: searchBar.build(context),
key: _scaffoldKey,
body: new Container(
color: Colors.grey[800],
child: new RefreshIndicator(
child: new ListView(
children: <Widget>[
new FutureBuilder<List<Post>>(
future: fetchPosts(URLWEB),
builder: (context, snapshot) {
if(snapshot.hasData) {
List<Post> posts = snapshot.data;
return new Column(
children: posts.map((post2) => new Column(
children: <Widget>[
new Card(
margin: new EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0),
color: Colors.white,
child: new GestureDetector(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new FutureBuilder(
future: fetchPostsIMG(post2.imagen),
builder: (context, AsyncSnapshot<PostImg> snapshot2){
return new Container(
height: 200.0,
decoration: new BoxDecoration(
image: new DecorationImage(
image: CachedNetworkImageProvider(snapshot2.data.imagen == null ? new AssetImage('images/logotipo.png') : snapshot2.data.imagen),
fit: BoxFit.fitWidth
)
),
width: MediaQuery.of(context).size.width,
);
},
),
new ListTile(
title: new Text(post2.titulo.replaceAll("‘", "").replaceAll(
"’", "").replaceAll("–", "")
.replaceAll("…", "").replaceAll(
"”", "")
.replaceAll("“", ""),
style: new TextStyle(
color: Colors.black,
fontSize: 18.0,
fontWeight: FontWeight.bold),),
subtitle: new HtmlView(data: post2.informacion),
dense: true,
)
],
),
onTap: () {
//Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new WebView(url: post2.urlweb, titulo: titulo)));
},
)
)
],
)).toList(),
);
}
else if(snapshot.hasError)
{
return new Container();
}
return new Center(
child: new Column(
children: <Widget>[
new Padding(padding: new EdgeInsets.all(50.0)),
new CircularProgressIndicator(),
],
),
);
},
),
],
),
onRefresh: _autoRefresh
),
),
);
}
}
It's because you are trying to access imagen on null object. You can do hasData check like below
CachedNetworkImageProvider(snapshot2.hasData ? snapshot2.data.imagen : new AssetImage('images/logotipo.png')),

ListView.builder Not Building Items (nothing is displayed)

When I don't use the ListView.builder constructor in Flutter, the individual item is shown as expected from the JSON API:
On the other hand, when I use ListView.builder, nothing shows up.
Here's the code:
import 'dart:ui';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart'as http;
import "package:flutter/material.dart";
import 'package:flutter/painting.dart';
Map responsee={};
bool _loading = false;
class tag extends StatefulWidget{
Map data={};
tag(this.data);
#override
State<StatefulWidget> createState() {
return tagstate(data);
}
}
class tagstate extends State<tag>{
List influ=[{"username":"tarun"}];
Map data={};
tagstate(this.data);
Future<Null> load()async {
responsee = await getJson1(data["tag"]);
setState(() {
_loading = true;
influ=responsee["influencers"];
new Future.delayed(new Duration(seconds: 5), _login);
});
print('length: ${influ}');
}
Future _login() async{
setState((){
_loading = false;
});
}
#override
void initState() {
load();
super.initState();
}
#override
build(BuildContext context) {
var bodyProgress = new Container(
child: new Stack(
children: <Widget>[
new Container(
alignment: AlignmentDirectional.center,
decoration: new BoxDecoration(
color: Colors.white70,
),
child: new Container(
decoration: new BoxDecoration(
color: Colors.blue[200],
borderRadius: new BorderRadius.circular(10.0)
),
width: 300.0,
height: 200.0,
alignment: AlignmentDirectional.center,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Center(
child: new SizedBox(
height: 50.0,
width: 50.0,
child: new CircularProgressIndicator(
value: null,
strokeWidth: 7.0,
),
),
),
new Container(
margin: const EdgeInsets.only(top: 25.0),
child: new Center(
child: new Text(
"loading.. wait...",
style: new TextStyle(
color: Colors.white
),
),
),
),
],
),
),
),
],
),
);
return Scaffold(
appBar: new AppBar(iconTheme: IconThemeData(color: Colors.black),backgroundColor: Colors.white,
title: Text("Stats",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600),),
),
body: _loading ? bodyProgress : new Column(children: <Widget>[
Flexible(child: ListView.builder(padding: const EdgeInsets.all(14.5),itemCount: influ.length,itemBuilder: (BuildContext context,int pos){
new ListTile(
title: Text(influ[pos]["username"],style: new TextStyle(fontSize: 17.9),),
leading: CircleAvatar(
backgroundColor: Colors.pink,
child: Image.network("${influ[pos]["photo"]}"),
),
);
}),)],),
);
}
}
Future<Map> getJson1(String data) async{
String apiUrl="https://api.ritekit.com/v1/influencers/hashtag/$data?client_id=a59c9bebeb5253f830e09bd9edd102033c8fe014b976";
http.Response response = await http.get(apiUrl);
return json.decode(response.body);
}
No matter how much I try, the error still persists.
The Scaffold loads, but the ListView.builder doesn't.
When I don't use the ListView.builder, the individual item is shown as expected from the JSON API.
Thank you everyone...
I actually forgot to return the Listtile in the Itembuiler Function..
Thanks Again
Future<Null> load()async {
responsee = await getJson1(data["tag"]);
influ=responsee["influencers"];
}
should be
Future<Null> load()async {
responsee = await getJson1(data["tag"]);
setState(() => influ=responsee["influencers"]);
}
await getJson1(data["tag"]); is async and needs to notify Flutter to rebuild when the response arrives.
Because load() is async, it's not sure what "tagstate.build()" does. My suggestion is to do the loading in the parent widget, then when the loading is done, pass influ to the tag widget. E.g.
onPress(() {
final influ = (await getJson1(data["tag"]))['influencers'];
Navigator.of(context).push(
(new MaterialPageRoute(builder: (context) {
return tag(influ: influe);
}));
}
Move List influ = [] into tagState class and use setState as above answer. Everything should work now.
Please refer this. influ was global variable initially because of which even setState will not work. If we want our Stateful widget to react based on some value, it should be its instance variable, not local variable and not global variable.

Flutter refresh data in my listview

UPDATE
This is the StreamBuilder code:
I am trying currently to update with a timer that runs a Stream.fromFuture which updates the data, but with the flicker and scroll weirdness.
new StreamBuilder(
initialData: myInitialData,
stream: msgstream,
builder: (BuildContext context, AsyncSnapshot<List<Map>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return new Text('Waiting to start');
case ConnectionState.waiting:
return new Text('');
default:
if (snapshot.hasError) {
return new Text('Error: ${snapshot.error}');
} else {
myInitialData = snapshot.data;
return new RefreshIndicator(
child: new ListView.builder(
itemBuilder: (context, index) {
Stream<List<Map>> msgstream2;
Future<List<Map>> _responseDate = ChatDB.instance.getMessagesByDate(snapshot.data[index]['msgkey'], snapshot.data[index]['msgdate']);
msgstream2 = new Stream.fromFuture(_responseDate);
return new StreamBuilder(
initialData: myInitialData2,
stream: msgstream2,
builder: (BuildContext context, AsyncSnapshot<List<Map>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return new Text('Waiting to start');
case ConnectionState.waiting:
return new Text('');
default:
List messList;
var mybytes;
File myimageview;
Image newimageview;
String imgStr;
String vidStr;
String vidimgstr;
myInitialData2 = snapshot.data;
List<dynamic> json = snapshot.data;
List messagelist = [];
json.forEach((element) {
DateTime submitdate =
DateTime.parse(element['submitdate']).toLocal();
String myvideo = (element['chatvideo']);
String myimage = element['chatimage'];
String myvideoimage = element['chatvideoimage'];
File imgfile;
File vidfile;
File vidimgfile;
bool vidInit = false;
Future<Null> _launched;
String localAssetPath;
String localVideoPath;
String mymessage = element['message'].replaceAll("[\u2018\u2019]", "'");
//print('MYDATE: '+submitdate.toString());
_checkFile(File file) async {
var checkfile = await file.exists();
print('VIDEXISTS: '+checkfile.toString());
}
Future<Null> _launchVideo(String url, bool isLocal) async {
if (await canLaunchVideo(url, isLocal)) {
await launchVideo(url, isLocal);
} else {
throw 'Could not launch $url';
}
}
void _launchLocal() =>
setState(() => _launched = _launchVideo(localVideoPath, true)
);
Widget _showVideo() {
return new Flexible(
child: new Card(
child: new Column(
children: <Widget>[
new ListTile(subtitle: new Text('Video'), title: new Text(element['referralname']),),
new GestureDetector(
onTap: _launchLocal,
child: new Image.file(
vidimgfile,
width: 150.0,
),
),
],
),
)
);
}
if (myimage != "") {
imgStr = element['chatimage'];
imgfile = new File(imgStr);
}
if (myvideo != "") {
vidStr = element['chatvideo'];
vidimgstr = element['chatvideoimage'];
vidimgfile = new File(vidimgstr);
localVideoPath = '$vidStr';
}
_showLgPic() {
Route route = new MaterialPageRoute(
settings: new RouteSettings(name: "/ShowPic"),
builder: (BuildContext context) => new ShowPic(
image: imgfile,
),
);
Navigator.of(context).push(route);
}
Widget _showGraphic() {
Widget mywidget;
if (myimage != "") {
mywidget = new GestureDetector(
child: new Image.file(
imgfile,
width: 300.0,
),
onTap: _showLgPic,
);
} else if (myvideo != "") {
mywidget = _showVideo();
} else {
mywidget = new Container();
}
return mywidget;
}
messagelist.add(
new Container(
//width: 300.0,
padding: new EdgeInsets.all(10.0),
child: new Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new Container(
padding: new EdgeInsets.only(bottom: 5.0),
child: new Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new CircleAvatar(
child: new Text(
element['sendname'][0],
style: new TextStyle(fontSize: 15.0),
),
radius: 12.0,
),
new Text(' '),
new Text(
element['sendname'],
style: new TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold),
),
new Text(' '),
new Text(
new DateFormat.Hm().format(submitdate),
style: new TextStyle(
color: Colors.grey, fontSize: 12.0),
),
],
),
),
new Row(
children: <Widget>[
new Text(' '),
new Flexible(
child: new Text(mymessage),
)
],
),
new Container(
width: 150.0,
child: new Row(
children: <Widget>[
new Text(' '),
_showGraphic()
],
)),
],
),
),
);
});
return new Column(children: messagelist);
}
}
);
/*return new MyChatWidget(
datediv: snapshot.data[index]['msgdate'],
msgkey: snapshot.data[index]['msgkey'],
);*/
},
//itemBuilder: _itemBuilder,
controller: _scrollController,
reverse: true,
itemCount: snapshot.data.length,
),
onRefresh: _onRefresh
);
}
}
}),
I started with a Future> from a local sqlite DB. I take that future and use the data to to get another Future> from the DB. I use Listview.builder to build the widget, etc... All works great, but need to refresh the data in realtime as messages come in and get updated in the DB. I converted the furtures to streams and use a timer to go get new data, but of course my screen flickers and eventhough the data refreshes its ugly.
So I am trying to figure out a better way to get the data to update without the flicker and not affect the user if they are scrolling on the page looking at messages.
I currently do the 2 futures, because one is used to build Date Dividers between messages for each Date. I have been looking at have a StreamController and subscribing to it, but not clear how to update the data in the controller as the the data needs to be full when they come to the page and then added to as the new messages sync.
So I have been looking at something like this that I found:
class Server {
StreamController<List<Map>> _controller = new StreamController.broadcast();
void addMessage(int message) {
var newmsg = await database.rawQuery('select c.*, date(submitdate, "localtime") as msgtime from v_groupchats g join chats c on c.id = g.id where (oid = $oid or prid = $prid) and c.msgkey not in (select msgkey from chatArchive) order by submitdate desc');
_controller.add(message);
}
Stream get messages => _controller.stream;
}
This is not complete, just hoping it helps someone with some ideas for me.
Thanks in advance for any help.
This flickering is most likely the result of your:
case ConnectionState.waiting:
return new Text('');
Because every time you fetch data, your stream will enter a brief moment of ConnectionState.waiting before it is ConnectionState.done. And what you did was tell the UI to display essentially nothing Text('') every time while it fetches data. Even if it only takes like 50ms, it's noticeable to the human eye...
So if you don't care while your stream is fetching data, then remove that check. Otherwise, you could change your layout into a Stack and overlay a loading animation somewhere, or just something to indicate that it's currently fetching data.
(note that I was able to see this flickering when I tried to test your setup with a simulated Future.delayed(const Duration(milliseconds: 50), () => data), and we can perceive quicker still)

Resources