1

I want to create a variable with dynamic value in it. Something like this:

String myAlphabet = 'c';
List myList = [
   'a',
   'b',
   getMyAlphabet()
];

String getMyAlphabet(){
   return myAlphabet;
}

When I access myList, I should get ['a','b','c']. But at one point of my program, the value of myAlpabet is changed to 'd'. At that point when I access myList I should be getting ['a','b','d'] but instead I'm still getting ['a','b','c'].

How do I make it so that everytime I access myList, I will be getting the latest value instead of the value when it is first initialized? Thank you in advance.

3 Answers 3

2
List myList = [
   'a',
   'b',
   getMyAlphabet()
];

getMyAlphabet() will be evaluated at the time that this List is created, and the result will be stored in the List.

If you want myList to always return a List with the latest evaluation of getMyAlphabet(), you could make myList create and return a new List each time by making it a getter function:

List get myList => ['a', 'b', getMyAlphabet()];

Note that you wouldn't be able to effectively mutate myList, which potentially could be surprising to callers.

Another approach would be to make myList a list of thunks so that they would need an extra level of evaluation:

List<String Function()> myList = [
  () => 'a',
  () => 'b',
  getMyAlphabet,
];

var a = myList[0]();
var lastElement = myList.last();
var list = [for (var thunk in myList) thunk()];

To take it further, you could create your own List-like class whose operator[] implementation invokes each thunk automatically instead of making callers do it.

Sign up to request clarification or add additional context in comments.

Comments

1

Hm... How about you use making a method to get a my List?


//
​
//

void main() {
  String myAlphabet = 'c';
  String getMyAlphabet(){
    return myAlphabet;
  }
  
  List<String> getMyList() {
    return [
      'a',
      'b',
      getMyAlphabet()
    ];
  }
  
  List myList = [
    'a',
    'b',
    getMyAlphabet()
  ];


  print(myList);
  print(getMyList());
  
  myAlphabet = 'd';
  
  print(myList);
  print(getMyList());
  

}


enter image description here

Comments

0

I believe you'll have to edit the List rather than try to create a "pointer" in the list, which I don't believe is possible with Dart.

List has a method called replaceRange (docs) which you could use to replace a value at a certain index in the list. There are other methods you could combine to do the same thing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.