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?

3 Answers 3

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) {
  ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Can you also take a look at stackoverflow.com/questions/66042050/… please
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)}");
}

3 Comments

Can I declare it cs w/ lambda syntax instead in main?
Yes, you can do that.
Using a typedef isn't strictly necessary (although it can be more readable). You also should prefer the modern typedef syntax which would make it clearer how to specify the type without using a typedef: typedef ConvertStringToDouble = double Function(String input);.
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);
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.