Home > Software engineering >  update elements of array dart
update elements of array dart

Time:08-10

I have this array using dart language .

  var array1 = ["1111" , "2222" ,"3333"];

if user click button I need to update array for example ; I want array to be like

array1 =  ["4444" , "1111" ,"2222"];

and if user click again

array1 =  ["5555" , "4444" ,"1111"];

I hope you understand what I mean . I don't know how can I do that

button code :

 child: ElevatedButton(
              onPressed: () {
                if(!_ischecked){
                updateArray();
                }else{
                  //
                }
              },

Future<void> updateArray() async {
    setState(() {
      _ischecked = true;
    });
  }

CodePudding user response:

If the goal is to add an element to the start of the list, and remove the last, you could do it as follows:

List<String> updateArray(List<String> array, String addToStartOfArray) {
  return array
    ..insert(0, addToStartOfArray)
    ..removeLast();
}

This method first add the string addToStartOfArray to the beginning of the list, and then removes the last element of the List.

You can use this method as follows:

void main() {
  var array = ["1111", "2222", "3333"];
  array = updateArray(array, "4444");
  print(array);
  array = updateArray(array, "5555");
  print(array);
}

CodePudding user response:

From what I understand your want to update the first index of your List with value incremented by 1111 to the previous highest value of the List. If this is not the algorithm, just check out the logic behind List manipulation.

// To find max in the List
import 'dart:math';

  var list1 = ["1111", "2222", "3333"];

  void updateList() {
    // Create new List<int> out the List<String> to easily find max & do the addition
    List<int> intList = list1.map(int.parse).toList();

    // The current max in the List
    int currentMax = intList.fold(0, max);

    // The new max in String
    String newMax = (currentMax   1111).toString();

    // Add the new max at the beginning of your List
    list1.insert(0, newMax);

    // Remove the last item so the List can have only three items
    list1.removeAt(3);

    print(list1);
    setState(() {});
  }

After 6 clicks prints :

[4444, 1111, 2222]
[5555, 4444, 1111]
[6666, 5555, 4444]
[7777, 6666, 5555]
[8888, 7777, 6666]
[9999, 8888, 7777]
  • Related