0

Say I need a function passed into a method which takes a String and turns it into a double:

void strToDouble(String input, Function converter) {
  print('As a double, $input is ${converter(input)}`);
}

(Obviously toy example)

How can I declare the type of converter as a function that turns a String to double?

Ali
  • 261,656
  • 265
  • 575
  • 769

3 Answers3

3

To declare your converter callback as a Function that takes a String and returns a double, its type should be: double Function(String). Therefore your strToDouble function would be:

void strToDouble(String input, double Function(String) converter) {
  ...
}
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • Thanks. Can you also take a look at https://stackoverflow.com/questions/66042050/flutter-integration-tests-for-ios-on-firebase please – Ali Feb 09 '21 at 06:46
1

You can use typedef

typedef double ConvertStringToDouble(String input);

void main() {
  ConvertStringToDouble cs = (String input){
    return double.parse(input);
  };
  
  strToDouble("29.0", cs);
}
void strToDouble(String input, ConvertStringToDouble converter) {
  print("As a double, $input is ${converter(input)}");
}
Tipu Sultan
  • 1,743
  • 11
  • 20
  • Can I declare it `cs` w/ lambda syntax instead in main? – Ali Feb 09 '21 at 05:55
  • Yes, you can do that. – Tipu Sultan Feb 09 '21 at 06:01
  • 1
    Using a `typedef` isn't strictly necessary (although it can be more readable). You also should [prefer the modern `typedef` syntax](https://dart.dev/guides/language/effective-dart/design#dont-use-the-legacy-typedef-syntax) which would make it clearer how to specify the type without using a `typedef`: `typedef ConvertStringToDouble = double Function(String input);`. – jamesdlin Feb 09 '21 at 06:33
1

This is the function you want to call to get the output as double by passing the string and the converter function:

  dynamic dynamicConverter (String input, double Function(dynamic input) convert){
    return convert.call(input);
  }

You will have to use it like below:

   double output = dynamicConverter("120", (input) {
      return double.parse(input);
    });
Gourango Sutradhar
  • 1,461
  • 10
  • 16