I was trying fetch api data with provider, but I am getting this error
Exception has occurred. RangeError (RangeError (index): Invalid value: Valid value range is empty: 1),
I was using previously listviewbuilder,so that I can access the data with index, but here I am not getting the idea, please guide me
class _MiddleSectionState extends State<MiddleSection> {
@override
void initState() {
getdata();
super.initState();
}
getdata() async {
likesdata = await Repos().getdata();
}
bool isLikebuttonPressed = false;
List<LikeModelData> likesdata = [];
@override
@override
Widget build(BuildContext context) {
//final likedData = Provider.of<CommentPageProvider>(context);
Size size = MediaQuery.of(context).size;
return ChangeNotifierProvider(
create: (context) => CommentPageProvider(),
child: Padding(
padding: const EdgeInsets.all(15.0),
child: Container(
width: size.width * 0.2,
height: size.height * 0.1,
child: Column(children: [
Consumer<CommentPageProvider>(
builder: (context, value, child) {
return Row(
children: [
TextWidgetCommentpage(
text: value.isLoading? likesdata[0].postId ?? "Likes ": 'data fetching' ),
// TextWidgetCommentpage(text:likesdata[0].postId.toString() ??"11"),
const Spacer(),
TextWidgetCommentpage(
text: '${widget.commentCount} comments')
],
);
},
),
error showing is Exception has occurred. RangeError (RangeError (index): Invalid value: Valid value range is empty: 1)
CodePudding user response:
Beacause likesdata
is null
. You need to use setState
to update value.
getdata() async {
setState(() { // use it like this
likesdata = await Repos().getdata();
});
}
Calling setState
notifies the framework that the internal state of this object has changed in a way that might impact the user interface in this subtree.
CodePudding user response:
I think that in 'likesdata' list has no data means that this list is empty that's why you are getting an error like this you also check whether the list is empty or not by putting print in the build method. Please handle the widget view as if
likesdata.isEmpty?SizedBox():YourWidgets()
and also API data getting let after build then you need to use setState after the fatching data
likesdata = await Repos().getdata();
setState((){});