Friday, June 9, 2023

Handling Unused Parameters in Dart

Handling Unused Parameters in Dart

In Dart, underscores are used to signify unused parameters. For instance, in the following code snippet, the second parameter of the function 'doSomething' is not used:


void doSomething(int a, _) {
  print(a);
}

In this situation, you can set the parameter name to _ to indicate that it's an unused parameter. Furthermore, if you don't use two arguments, you can write your code like this:


void doSomething(_, __) {
  print("Both parameters are unused!");
}

Recommendations from Dart Style Guide

The Dart style guide suggests using _, __ etc. for naming unused callback parameters. This is a conventional way of indicating that a value isn't being used.

Dart and Lists

Here's an example of handling lists:


var list = ['apples', 'bananas', 'oranges'];
list.forEach((item) {
  print(item);
});

In the above code snippet, list.forEach calls an anonymous function it receives as an argument for each item in the list. This is written in a neat and concise manner but if you don't use the argument item inside your function then you can replace it with an underscore.


var list = ['apples', 'bananas', 'oranges'];
list.forEach((_) {
  print("Fruit!");
});

In this example above, we ignore our argument and print "Fruit!". Thus in Dart we can use underscores to mark unused parameters and if there are more than two discarded arguments then we can use additional underscores like '__'.


0 개의 댓글:

Post a Comment