skip to Main Content

I have a confusion regarding passing list to a function in dart

here i have made two example to clear my query

in first example
when i passed a list to function and add some new values to list…it updates void main’s list. thats fine like passing byref

but in another example,
when i pass a list to function and applying him brand new list ..it does not update void main’s list..why?

where should i get documentation regarding this…its long time i am confused in byval and byref while passing list or object

void update(List<String> list)
{
  list.add('C');
}
void main()
{
  List<String> list=['A','B'];
  print('Before'+list.toString());
  update(list);
  print('after'+list.toString());
}
//Before[A, B] after[A, B, C] means updating void main's list

Program 2


void update(List<String> list)
{
  List<String> newList=['x','y'];
  list=newList;
}
void main()
{
  List<String> list=['A','B'];
  print('Before'+list.toString());
  update(list);
  print('after'+list.toString());
}

//Before[A, B] after[A, B] here not updating void main's list, and why?

5

Answers


  1. In the second example, you’re affecting locally the value of your parameter "list" a new value within the scope of your function because list are passed by reference to functions. In order for this to work you would either :

    • need to make your update function return a new list that you affect to your list in the main function

    • use .addAll() / .clear() methods on the list given as parameter of your updateFunction

    First solution

    List<String> update(List<String> list)
    {
      List<String> newList=['x','y'];
      return newList;
    }
    void main()
    {
      List<String> list=['A','B'];
      print('Before'+list.toString());
      list = update(list);
      print('after'+list.toString());
    }
    

    Second solution

    void update(List<String> list)
    {
      List<String> newList=['x','y'];
      list.clear();
      list.addAll(newList);
    }
    void main()
    {
      List<String> list=['A','B'];
      print('Before'+list.toString());
      update(list);
      print('after'+list.toString());
    }
    
    Login or Signup to reply.
  2. In Dart, when you pass an object (including lists) to a function, you are passing a reference to the object. Modifying the object via this reference will reflect outside the function. However, if you reassign a new object to the parameter, it only changes the local reference within the function and does not affect the original reference.

    I will explain you in detail

    void appendToList(List<int> numbers) {
      numbers.add(3);
    }
    
    void main() {
      List<int> myNumbers = [1, 2];
      print('Before: $myNumbers'); // Output: Before: [1, 2]
      appendToList(myNumbers);
      print('After: $myNumbers');  // Output: After: [1, 2, 3]
    }
    
    • myNumbers is a list containing [1, 2].

    • appendToList is called with myNumbers as an argument.

    • Inside appendToList, the add method modifies the original list by
      adding 3.

    • The modification is reflected in the myNumbers list in main.

         void replaceList(List<int> numbers) {
             List<int> newNumbers = [7, 8];
             numbers = newNumbers;
           }
      
           void main() {
             List<int> myNumbers = [1, 2];
             print('Before: $myNumbers'); // Output: Before: [1, 2]
             replaceList(myNumbers);
             print('After: $myNumbers');  // Output: After: [1, 2]
           }
      
    • myNumbers is a list containing [1, 2].

    • replaceList is called with myNumbers as an argument.

    • Inside replaceList, a new list [7, 8] is created and assigned to the
      local variable numbers.

    • This reassignment does not affect myNumbers in main because it only
      changes the local reference inside the replaceList function.

    Login or Signup to reply.
  3. Copy of a reference variable (pointer) is passed to parameter

    Example 1 is already understood, let’s explain exmple2:

    when you are calling that function like that: update(list);

    a copy of the reference variable list is passed to the parameter update(List<String> list) list in the method signature.

    an image holds a thousand words, which leads to that:

    enter image description here

    Ok, your program now has two reference variables which are pointing to the same memory location, imagine you have done this:

    list = ['x' , 'y'];
    

    your local list variable (in update function) will not change that list, instead it will point to another one ['x' , 'y']:

    which leads to the following:

    enter image description here

    and the list which is defined in the main still the same.

    Login or Signup to reply.
  4. void main() 
    {
      List<String> list=['A','B'];
      print('Before'+list.toString());
      update(list);
      print('after'+list.toString());
    }
    
    void update(List<String> list)
    {
    
       List<String> newList=['x','y'];
      // first clear all the list
       list.clear();
      //replace the list you want 
       list.addAll(newList);
    
    }
     

    The reason why it is not updating in the main is because , in main you have declared the list and print the List , then you’ve called the update function which is passing the reference of list , and in update function you are updating the list , so the change will be only to reference not to the Original list , so in main there is not any change t the list , Here’s the one solution you can go with .

    Login or Signup to reply.
  5. your confusion is right but just keep in mind that while giving brand new object or brand new list to passed argument it will not affect original list or original object,

    but while adding or deleting list member or object’s property it will update original list..

    In Short ,
    consider as by value while giving brand new list or new object to passed argument // will not effect original list

    and
    consider as by reference while just adding or updating its member
    // will effect original list

    Exmaple 1:

    class User
    {
      String name;
      User({required this.name});
    }
    
    void update(User u)
    {
      u.name='X';//will update main's user u
    }
    void main()
    {
      User u=User(name: 'A');
      print('Before : '+u.name);
      update(u);
      print('After : '+u.name);
    
    }
    
    //output  Before : A After : X
    

    Example : 2

    void update(User u)
    {
     u=User(name: 'X');//will not update main's user u
    
    
    }
    void main()
    {
      User u=User(name: 'A');
      print('Before : '+u.name);
      update(u);
      print('After : '+u.name);
    }
    //output  Before : A After : A
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search