iDecode
iDecode

Reputation: 28876

How to return multiple values from function in Dart?

Say I have:

Function(int x, int y) func = (int x, int y) {
  return (1, 2); // error
};

How to actually return (1, 2) from above function?

Upvotes: 6

Views: 5952

Answers (2)

Tariqali
Tariqali

Reputation: 379

Now you can return multiple values from function in Dart 3.0 with Record feature.

 (int, int) testFunc(int x, int y) {
     return (1, 2);
   }

Destructures using a record pattern

 var (x, y) = testFunc(2,3);
 print(x); // Prints 1
 print(y); // Prints 2

Upvotes: 3

julemand101
julemand101

Reputation: 31199

Methods in Dart can only return one value. So if you need to return multiple values you need to pack them inside another object which could e.g. be your own defined class, a list, a map or something else.

In your case with x and y you could consider using the Point class from dart:math:

import 'dart:math';

Point<int> func(int x, int y) => Point(x, y);

Support for returning multiple values in Dart are a ongoing discussion here: https://github.com/dart-lang/language/issues/68

Upvotes: 8

Related Questions