Dart
Putting it together
Combine helper methods into a library.
Putting it together
In the final lesson we'll call all three helpers together. slugify tidies strings, clamp bounds numbers, formatDate formats dates. All work on a single Helper instance.
We'll create one instance and call the three methods in turn: var h = Helper();, h.slugify(...), h.clamp(...), h.formatDate(...). Each call gives one line of output. This shows the library in action. We'll also add a library directive at the top of the file to mark it as a named library.
library and export
In Dart the library directive turns a file into a named library: library helpers;. This gives the file a name and makes it easy to import from other files.
A related concept is export: it re-publishes symbols from another library through your own. For example export 'src/string_helpers.dart'; exposes the public symbols of that file through your library. Since we work in a single file in this lesson we do not use export directly; but it is an important tool in library design and in real projects it bundles many files under one interface.
Exercise Combine the library
Keep the existing Helper class. Add a library helpers; directive at the very top of the file. In main, create an instance with var h = Helper(); and call the three helpers in turn: print(h.slugify('Hello World')), print(h.clamp(15, 0, 10)) and print(h.formatDate(2024, 5, 1)).
Show example solution
library helpers;
class Helper {
final String version;
Helper() : version = '1.0';
String slugify(String text) {
return text.toLowerCase().replaceAll(' ', '-');
}
int clamp(int value, int min, int max) {
if (value < min) return min;
if (value > max) return max;
return value;
}
String formatDate(int year, int month, int day) {
var m = month.toString().padLeft(2, '0');
var d = day.toString().padLeft(2, '0');
return '$year-$m-$d';
}
}
void main() {
var h = Helper();
print(h.slugify('Hello World'));
print(h.clamp(15, 0, 10));
print(h.formatDate(2024, 5, 1));
}
Test yourself
-
Which call works on a Helper instance?
- h.slugify('Hello')
- Helper.slugify('Hello')
- slugify('Hello')
- h(Helper.slugify)
Show answer
h.slugify('Hello') — Instance methods are called as h.method().
-
Match the helpers
- slugify
- String helper
- clamp
- Number helper
- formatDate
- Date helper
-
Complete the library directive
library ____;
class Helper { ... }
Show answer
library helpers;
class Helper { ... }
Next lesson: private