Reputation: 43
I'm fetching some json data from the internet and displaying in a listview builder inside a stateless widget
Now I want to refresh the data using RefreshIndicator. Do I need a stateful widget for this or can I manage to do this with a stateless widget?
My understanding:
If I don't need to refresh, I load the data from internet only on the app start up, So Stateless widget is enough
If I need to refresh, it involves user input, but I don't need to manage a state, I just need to re-run the build method (Which I plan to do by Navigating to the same page, in the onRefresh parameter of RefreshIndicator)
So do I need a stateful widget?
Upvotes: 1
Views: 1200
Reputation: 153
Because you want to reduce the StatefulWidget instances, you can delegate the task of fetching data to a parent stateful widget. You could pass a callback to perform the task of fetching data via the constructor of the StatelessWidget invoked whenever we want to refresh the data.
class _ParentWidgetState extends State<ParentWidget>{
...
Future<dynamic> _fetchData(){..}
...
Widget build(BuildContext){
return Container(
...
ChildWidget(onRefresh:_fetchData)
...
);
}
}
class ChildWidget extends StatelessWidget{
ChildWidget({Key? key,this.onRefresh}):super(key:key);
final Future<dynamic> Function() onRefresh;
...
@override
Widget build(BuildContext context){
return RefreshIndicator(
onRefresh:onRefresh,
child:..
);
...
}
}
The point is to delegate the task of loading the data to a parent StatefulWidget's state so you could use other mechanisms like ChangeNotifier to make the parent widget's state call the API and render after calling setState future in its own state.
Upvotes: 0
Reputation: 181
If you need a RefreshIndicator to get again the jsondata from the internet you must need a StateFullWidget because u need to rebuild the page with the newdata. There is no point in showing the indicator if you are not going to ask for new information.
Upvotes: 0
Reputation: 11
You must change the StatelessWidget to a StatefullWidget and use the function setState (){} to
Upvotes: 1