how to dynamically update ListView.builder() in Flutter?
840
Solution 1
you have two possible approaches:
- pass a function from
parent widget
to thechild widget
. then you can use it to change thestate
of parent directly:
// in parent widget define a function
void parentSetState(){
setState((){});
//also you can add your own code too
}
// then in child widget use this function
MaterialButton(onPressed: () {
setState(() {
myMap[index] = index * 2;
widget.parentSetState();
}
}, child: Text('Modify')),
- use state managements like
provider
. Personally, I prefer to use this approach. see this link
Solution 2
Where you call the Next widget it wrap with the inkwell and write the set stae method under inkwell instead of next widget
InkWell(
onTap: (){
setState(() {
/// write your code
});
},
child: NextWidget(),
)
Author by
Hamza Amr
Updated on December 31, 2022Comments
-
Hamza Amr over 1 year
I want to render a ListView dynamically. If a value changes in the list, I have to manually hot reload the application using my IDE for the changes to apply. I have tried using StreamBuilder, but the syntax was so complex.
Here's my code:
ListView.builder( physics: NeverScrollableScrollPhysics(), itemCount: myMap.length, shrinkWrap: true, itemBuilder: (context, index) { return myMap.values.elementAt(index) == true ? Container( padding: EdgeInsets.only(left: 20, right: 20, top: 20), child: Container(child: Text(myMap.keys.elementAt(index))) : Container(); }),
My stateful widget:
import 'package:flutter/material.dart'; class NextWidget extends StatefulWidget { NextWidget({Key? key}) : super(key: key); @override _NextWidgetState createState() => _NextWidgetState(); } class _NextWidgetState extends State<NextWidget> { @override Widget build(BuildContext context) { return Container( child: MaterialButton(onPressed: () { setState(() { myMap[1] = 'Modified Value'; } }, child: Text('Modify')), ); } }
-
Jahidul Islam over 2 yearsyou can try with setState to rebuild the ui again and then you will get your update data.
-
Hamza Amr over 2 yearsWhere should I put the
setState(() {})
? -
Jahidul Islam over 2 yearsyou use setstate where you could change your value? otherwise you can share code.
-
Hamza Amr over 2 yearsInside another stateful widget
-
Jahidul Islam over 2 yearscan you share your code part?
-
Hamza Amr over 2 yearsI shared it in the edit
-
Hamza Amr over 2 yearsIt isn't useful
-
Jahidul Islam over 2 yearsboth modify button and listview.builder in same page
-
Hamza Amr over 2 yearswhat do you mean
-
Hamza Amr over 2 yearsOk I added it in the edit
-
Hamza Amr over 2 yearsYes, because the
setState(() {})
is in a different Stateful Widget.
-
-
Abbasihsn over 2 yearshappy to hear it. I suggest trying to work with
state management
as well. This concept would help you to have access to each data wherever you want. However, for a simple projects first solution works well.