Home > Mobile >  Not able to update a list with set state in textfield onchanged method
Not able to update a list with set state in textfield onchanged method

Time:10-25

i want to update a list of songmodel when i enter a value in textfield with on changed model the value is not updating of list with set state method

List<SongModel> songs = item.data!;
              List<SongModel> filterSongs = [];
              //showing the songs
              return Column(
                mainAxisSize: MainAxisSize.max,
                children: [
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: TextField(
                      keyboardType: TextInputType.text,
                      controller: searchController,
                      onChanged: (value) {
                        //pass value for the search
                        getSearch(filterSongs,songs);
                      },
                      decoration: InputDecoration(............

function of getSearch :-

getSearch(List<SongModel> filterSongs,List<SongModel> songs)
{
  var text = searchController.text;
  if (text.isEmpty) {
    setState(() {
      filterSongs = songs;
    });
  }
  print(songs.where((SongModel item) => item.title.toLowerCase().contains(text.toLowerCase())).toList());
  print(text);
  setState(() {
    // search = text;
    filterSongs = songs.where((SongModel item) => item.title.toLowerCase().contains(text.toLowerCase())).toList();
  });
  print(filterSongs.length);
}

here the list is not updating with set state method.

CodePudding user response:

In your getSearch method, you are setting the value of the parameter passed to getSearch, not the value of the list outside of that method. You should move the filterSongs list declaration outside of your build method anyways so that it isn't redeclared every time the screen is rebuilt.

class MyScreenClassState extends State<MyScreenClass>{
    //Create State method here
    

    List<SongModel> filterSongs = [];

    //Build method here

}
getSearch(List<SongModel> songs)
{
  var text = searchController.text;
  if (text.isEmpty) {
    setState(() {
      filterSongs = songs;
    });
  }
  print(songs.where((SongModel item) => item.title.toLowerCase().contains(text.toLowerCase())).toList());
  print(text);
  setState(() {
    // search = text;
    filterSongs = songs.where((SongModel item) => item.title.toLowerCase().contains(text.toLowerCase())).toList();
  });
  print(filterSongs.length);
}

CodePudding user response:

If onChanged method doesn't work for your implementation, you can try this structure I think I will work for you.

 final TextEditingController _controller = TextEditingController();

 
@override
  void initState() {
    super.initState();
    _controller.addListener(_onControllerChange);
    
  }

@override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

 void _onControllerChange() async {

.....


}
  • Related