how to use debugPrint for image.network? - flutter

I want to see the link of the image in the terminal using debugPrint.
kindly help me.
This is my code:
FutureBuilder<Iterable<SubCategories>>(
builder: (context, snapshot) {
return ListView.builder(
itemBuilder: (context, index) =>
Image.network(
snapshot.data!.elementAt(index).logo,
),
);
}),

Try out this:
**Note:** import log as **dart.developer** (import 'dart:developer';)
FutureBuilder<Iterable<SubCategories>>(
builder: (context, snapshot) {
return ListView.builder(
itemBuilder: (context, index) {
log("Network image--->${snapshot.data!.elementAt(index).logo}");
return Image.network(
snapshot.data!.elementAt(index).logo,
),
}
);
}),

debugPrint only takes String as argument.
you can do something like this.
debugPrint('${snapshot.data!.elementAt(index).logo}');

Related

Is there any way to make it -> snapshot.data[index].variable in flutter?

In flutter if i wanted to print the values using FutureBuilder
I have to write this 3 line individually
snapshot.data[index].courseName ,
snapshot.data[index].coursePrice,
snapshot.data[index].aboutCourse
So, Is there any way to make a list like this -> fieldItem = ['courseName' , 'coursePrice' , 'aboutCourse'] and then pass fieldItems after the .data[index].{our varibles}
**snapshot.data[index].fieldItems**
varibles will be passed through the fieldItem.
Sorry for my bad english
body: FutureBuilder(
future: _loadData(),
builder: (BuildContext ctx, AsyncSnapshot<List> snapshot) {
if(snapshot.hasData) {
// You can make variable here
// final _data = snapshot.data;
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (BuildContext context, index) {
// Or as in your case
final _data = snapshot.data![index];
return Card(
margin: const EdgeInsets.all(10),
// render list item
child: ListTile(
contentPadding: const EdgeInsets.all(10),
title: Text(_data['title']),
subtitle: Text(snapshot.data![index]['body']),
),
),
}
);
} else {
return const Center(child: CircularProgressIndicator());
}
}
);
Refer 11th line, if it helps, upvote.

Why is there an error with snapshot.data.length?

I am trying to parse data from an API. For that, I am using FutureBuilder to list all the parsed data in a ListView.
I've performed a check for nullity of snapshot.data but I keep on getting this error in the segment snapshot.data.length, it says, The property 'length' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.') or adding a null check to the target ('!').
I've a similar error in the snapshot.data[i] section, which says The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!').
Here is my code's section of the same:
body: Container(
child: FutureBuilder(
future: getData('hello'),
builder: (context, snapshot) {
if (snapshot.data == null) {
return Container(
child: Text("Loading"),
);
}else{
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, i) {
return ListTile(
title: snapshot.data[i].partOfSpeech,
);
});
}
},
),
),
Here's getData(String s):
Future<List> getData(String s) async {
var response = await http
.get(Uri.https('api.dictionaryapi.dev', 'api/v2/entries/en_US/' + s));
var jsonData = jsonDecode(response.body)[0];
List<Data> data = [];
for (var x in jsonData["meanings"]) {
String definition = x["definitions"][0]["definition"];
Data d = Data(x["partOfSpeech"], definition);
data.add(d);
}
return data;
}
if u are using a new version of flutter (2.2.0 or above). first try adding a null check to the target ('!'). because of the null safety feature.
body: Container(
child: FutureBuilder(
future: getData('hello'),
builder: (context, snapshot) {
if (snapshot.data == null) {
return Container(
child: Text("Loading"),
);
}else{
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, i) {
return ListTile(
title: snapshot.data[i].partOfSpeech,
);
});
}
},
),
),
then try specifying the FutureBuilder type to a List of Data type
body: Container(
child: FutureBuilder<List<Data>>(
future: getData('hello'),
builder: (context, snapshot) {
if (snapshot.data == null) {
return Container(
child: Text("Loading"),
);
}else{
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, i) {
return ListTile(
title: snapshot.data[i].partOfSpeech,
);
});
}
},
),
),
In continuation to this answer,
I found the solution to my problem. Apparently getData was not returning a List as intended. Instead, it was returning an Object.
Typecasting the Object to List solved the problem.
Here's the corrected code:
body: Container(
child: FutureBuilder(
future: getData('hello'),
builder: (context, snapshot) {
if (snapshot.data == null) {
return Container(
child: Text("Loading"),
);
}else{
//typecasting Object to List
var data = (snapshot.data as List<Data>).toList();
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, i) {
return ListTile(
title: data[i].partOfSpeech,
);
});
}
},
),
),
Put 'AsyncSnapshot' before snapshot in the builder parameter.
builder: (context, AsyncSnapshot snapshot)
Since you are checking that snapshot.data is not null you can do the following to fix it.
body: Container(
child: FutureBuilder(
future: getData('hello'),
builder: (context, snapshot) {
if (snapshot.data == null) {
return Container(
child: Text("Loading"),
);
} else{
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, i) {
return ListTile(
title: snapshot.data[i]!.partOfSpeech,
);
});
}
},
),
),
What you need to look at is the result of getData('hello')
Apparently, it does not return something that has a length property.

Error: the operation '[]' is not defined for the type 'object'

I am using Null -Safety then I keep getting this error, anywhere I user snapshot in my code
here is the error
here is my code
StreamBuilder(
stream: firestore
.collection('interest')
.doc('${auth.currentUser?.uid}')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: snapshot.data!['Interest'].length ,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.only(top: 12.0),
child: bottomCardList(
'assets/1 (6).jpeg',
snapshot.data!['Interest'][index]
.toString(),
),
);
});
}),
Thanks
i solve this by using the type
StreamBuilder<DocumentSnapshot<Map>>(
stream: firestore
.collection('interest')
.doc('${auth.currentUser?.uid}')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: snapshot.data!['Interest'].length ,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.only(top: 12.0),
child: bottomCardList(
'assets/1 (6).jpeg',
snapshot.data!['Interest'][index]
.toString(),
),
);
});
}),
There are a few solutions:
Provide a type to your StreamBuilder:
StreamBuilder<DocumentSnapshot<Map>> (...)
Provide a type to the second parameter of your builder:
builder: (context, AsyncSnapshot<Map> snapshot)
Use as to downcast the Object to Map
(snapshot.data as Map)['key']

Flutter combine futuerbuilder and streambuilder

i need some guidance how to combine a futurebuilder with a streambuilder. For example, the futurebuilder will load the comments which are stored in my Mysql database, while the streambuilder will fetch new comments and add them to the listview. The stream and future works perfectly, but i have no idea how i will combine these two things with eachother.
FutureBuilder(
future: _fetchComments(39),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
return Container(
height: 150,
child: StreamBuilder(
stream: commentProvider.channel.stream,
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot2) {
return ListView.builder(
key: PageStorageKey("CommentsScroll"),
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
final comment = snapshot.data[index];
return CommentTile(
key: Key(DateTime.now().toString()),
photoUrl: comment["photo_url"],
displayName: comment["display_name"],
created: comment["created"],
text: comment["text"],
);
},
);
},
),
);
},
),

FutureBuilder inside ListView.builder not working

Want to display items using FutureBuilder inside a ListView.builder. However, theres no display. help pls
body: ListView.builder(
itemExtent: 25.0,
itemCount: _posts.length,
itemBuilder: (BuildContext context, int index){
Post post = _posts[index];
return FutureBuilder(
future: DatabaseService.getUserWithId(post.authorId),
builder: (BuildContext context, AsyncSnapshot snapshot) {
return Container(
height: 200.0,
margin: EdgeInsets.all(10.0),
color: Colors.red,
);
},
);
},
),