Task: Add TextFormatter function to format the string with args
This commit is contained in:
parent
a4264bb5e2
commit
5f282e4b59
@ -26,4 +26,5 @@
|
||||
|
||||
## 1.0.6
|
||||
- Add async function support
|
||||
- Add functions for set and remove for system config and file functions
|
||||
- Add functions for set and remove for system config and file functions
|
||||
- Add TextFormatter for format the string with args
|
14
example/text_formatter_example.dart
Normal file
14
example/text_formatter_example.dart
Normal file
@ -0,0 +1,14 @@
|
||||
import 'package:configurable/text_formatter.dart';
|
||||
|
||||
void main(List<String> args) {
|
||||
var text1 = 'Hello, {0}, then do this it by {1}!';
|
||||
var text2 = 'Hello, {firstName}, then do this it by {lastName}!';
|
||||
var result1 = TextFormatter(text1).format(['Sambo', 'Chea']);
|
||||
var result2 = TextFormatter(text2).decorate({
|
||||
'firstName': 'Sambo',
|
||||
'lastName': 'Chea',
|
||||
});
|
||||
|
||||
print('Result 1 => $result1');
|
||||
print('Result 2 => $result2');
|
||||
}
|
33
lib/text_formatter.dart
Normal file
33
lib/text_formatter.dart
Normal file
@ -0,0 +1,33 @@
|
||||
class TextFormatter {
|
||||
String? text;
|
||||
|
||||
TextFormatter(String? text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
String? format(List<dynamic> args) {
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var msg = text;
|
||||
args.asMap().forEach((index, element) {
|
||||
msg = msg?.replaceAll('{$index}', element);
|
||||
});
|
||||
|
||||
return msg;
|
||||
}
|
||||
|
||||
String? decorate(Map<String, dynamic> args) {
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var msg = text;
|
||||
args.forEach((index, element) {
|
||||
msg = msg?.replaceAll('{$index}', element);
|
||||
});
|
||||
|
||||
return msg;
|
||||
}
|
||||
}
|
15
test/text_formatter_test.dart
Normal file
15
test/text_formatter_test.dart
Normal file
@ -0,0 +1,15 @@
|
||||
import 'package:configurable/text_formatter.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
test('text formatter function format', () {
|
||||
var text1 = 'Hello, {0}!';
|
||||
var result1 = TextFormatter(text1).format(['Sambo']);
|
||||
|
||||
var text2 = 'Hello, {name}!';
|
||||
var result2 = TextFormatter(text2).decorate({'name': 'Chea'});
|
||||
|
||||
expect('Hello, Sambo!', result1);
|
||||
expect('Hello, Chea!', result2);
|
||||
});
|
||||
}
|
Loading…
Reference in New Issue
Block a user