Flutter: How to Update Specific Value in a List

oflutter.com - update value in the list

In this quick tutorial, I will show you how to update a value in a list using a dart programming language. Unfortunately, there is no method update() in the list, so we have to handle this by ourselves. Luckily, I will show you how to do this in a single line of code with validation.

Dart: Updating Value in the List<String>

For simplicity, let’s update a specific value in a List of strings.

 List<String> myList = ['Hello', 'World', 'I', 'Love', 'Dart'];

We will update the value ‘Love‘ with ‘Learn‘. To do so, we can achieve that by the code snippet below:

void main() {
  List<String> myList = ['Hello', 'World', 'I', 'Love', 'Dart'];
  
  // The string that we want to replce
  String findString = 'Love';
  // The string that we want to be replaced by
  String replaceWith = 'Learn';
   
  // Updating Value in the List
  myList.contains(findString) ? myList[myList.indexWhere((v) => v == findString)] = replaceWith : myList;

  // Print list: Output: [Hello, World, I, Learn, Dart]
  print(myList);
  
}

if you take a closer look, we achieved a value updating by a single line of code

  myList.contains(findString) ? myList[myList.indexWhere((v) => v == findString)] = replaceWith : myList;

In addition, by using myList.contains(findString) we have validated first that the list contains the value that we want to update.

You May Also Like

Leave a Reply

Your email address will not be published.

five × 2 =