Ad

How To Dynamically Update ListView.builder() In Flutter?

- 1 answer

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')),
        );
      }
    }
Ad

Answer

you have two possible approaches:

  1. pass a function from parent widget to the child widget. then you can use it to change the state 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')),
  1. use state managements like provider. Personally, I prefer to use this approach. see this link
Ad
source: stackoverflow.com
Ad