Home > Blockchain >  how to dynamically update ListView.builder() in Flutter?
how to dynamically update ListView.builder() in Flutter?

Time:09-17

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

CodePudding user response:

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(),
          )

CodePudding user response:

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
  • Related