Search code examples
dartflutterstringbuffer

StringBuffer in flutter doesn't working as expected


I am currently just started a Flutter project and is found quite frustrated when playing around with the StringBuffer class, I am having the below codes which format and apply the url to my class;

Connector._baseUri = baseUri;
if (Connector._baseUri.endsWith("/"))
  Connector._baseUri = Connector._baseUri.substring(0, Connector._baseUri.lastIndexOf('/'));
Connector._baseUri = new StringBuffer([Connector._baseUri, "/"]).toString();

However the initial value of baseUri is http://locahost/test////, but the final value of _baseUri is then be settled as [http://localhost/test, /] which I may expect a simple http://localhost/test/, have also tried .write() and .writeAll(), any help will be appreciated


Solution

  • StringBuffer has an optional parameter in the constructor, which will take any object and call toString() on it. The result of your code above is just toString() on a List. If you want to write an Iterable to the buffer, you instead want to use StringBuffer.writeAll which will iterate over the values and add each string to the buffer.

    final buffer = new StringBuffer();
    buffer.writeAll([Connector._baseUri, "/"]);
    return buffer.toString()
    

    Although with only two values you could also just use string interpolation instead.

    return '${Connector._baseUri}/';