1
votes

I am trying to create a method in dart but have run into a wall. I was looking at how .toUpperCase(); and .toLowerCase(); were done. The method that I am trying to create is .capitalize();

I would like to call this method like this String hello = "WORLD".capitalize(); //World

Here is the code I have so far

String capitalize() {
return this.codeUnitAt(0).toUpperCase() + this.substring(1).toLowerCase();
}

When running String hello = "WORLD".capitalize(); I get the following error

[38;5;124m[2015-6-4 11:37:13.011] Class 'String' has no instance method 'capitalize'.

NoSuchMethodError: method not found: 'capitalize'
Receiver: "WORLD"
Arguments: [][0m

I know i can call a function like String capitalize(String s) => s[0].toUpperCase() + s.substring(1); But would much rather keep string Manipulation calls the same.

Thanks and I appreciate any help:)

4
You would need fot example extension methods to do this which Dart doesn't have (yet). - Günter Zöchbauer

4 Answers

3
votes

You cannot extend the String class like you want. Just use it like this:

capitalize("WORLD");
0
votes

Yes, not like JS, you can't just change any class in Dart. You can extend it only. E.g. you can create MyString class with capitalize method. But I don't think you want it. Just make some StringUtils.dart library with method capitalize

0
votes

Since dart is more common now, there are a lot more packages available at pub.dartlang.org.

I found a nice dart package for different operation on strings. It also contains a capitalize method.

https://pub.dartlang.org/packages/basic_utils

Simply add the dependency :

dependencies:
   basic_utils: ^1.0.3

Usage :

StringUtils.capitalize("helloworld"); // helloworld => Helloworld

It also contains other usefull methods :

  • camelCaseToUpperUnderscore
  • camelCaseToLowerUnderscore
  • isAscii
  • isNullOrEmpty ...
0
votes

if this is still a problem, you can simple use this dependecy:

dependencies:
  text_tools: ^0.0.2

Is simple to use, here is an example:

//This will put the first letter in UpperCase, will print 'Name'
      print(TextTools.toUppercaseFirstLetter(text: 'name'));