Search code examples
functionreturndart

Return multiple values from function


Is there a way to return several values in a function return statement (other than returning an object) like we can do in Go (or some other languages)?

For example, in Go we can do:

func vals() (int, int) {
    return 3, 7
}

Can this be done in Dart? Something like this:

int, String foo() {
    return 42, "foobar";
} 

Solution

  • Updated for Dart 3.0

    In Dart 3.0 records can be used

    (int, String) foo() {
        return (42, "foobar");
    } 
    
    void main() {
      var (a,b) = foo();
      print("int: ${a}");
      print("String: ${b}");
    }
    

    Original answer

    Dart doesn't support multiple return values.

    You can return an array,

    List foo() {
      return [42, "foobar"];
    }
    

    or if you want the values be typed use a Tuple class like the package https://pub.dev/packages/tuple provides.

    See also either for a way to return a value or an error.