dartdestructuring

Destructuring in Dart not working as expected


I am going through the language tour and, coming from a mostly Javascript background, I'm having trouble understanding how to destructure this record.

(int, String, {String b, String c}) rec = (7, c:"testc", "positionaltest", b:"testb");
String (:b) = rec; 
print(b); // Expecting "testb"

Apparently, Dart is trying to assign the entire record rather than destructuring, because if I try to grab a positional value instead, it doesn't throw an error. Instead, it assigns the entire record to the variable.

(int, String, {String b, String c}) rec = (7, c:"testc", "positionaltest", b:"testb");
String (a) = rec; 
print(a); // Expecting 7

So far I've only gotten to the Records page, and this is my first encounter with destructuring in Dart.

Why are my examples not working as I expect, and what is the correct way to do them?

Using Dart 3.4.4


Solution

  • In order to destructure the record, the pattern on the left side must match the record:

    void main() {
      (int, String, {String b, String c}) rec =
          (7, c: "testc", "positionaltest", b: "testb");
      
      // The pattern on the left must match the structure of the record. 
      // To omit variables one may use the underscore character.
      var (i, _, :b, c:_) = rec;
      
      print(i); // Prints: 7
      print(b); // Prints: "testb"
      
    }
    

    For more info, see record and patterns.