Search code examples
flutterjoinpath

Flutter: path.join is not joining strings


I am using the join function from the package path.dart to build a file path. However it doesn't seem to be joining the strings, and just returns the last one.

For example:

import 'package:path/path.dart' as path;

String _docsDir = (await getApplicationDocumentDirectory()).path;
String xmlRelativePath = '/xmlfiles/myfile.xml';
String xmlFullPath = '';

xmlFullPath = path.join(,_docsDir, xmlRelativePath );           // outputs: /xmlfiles/myfile.xml

xmlFullPath = path.join('ARRRRGGG',_docsDir, xmlRelativePath ); // outputs: /xmlfiles/myfile.xml

but if I just paste them together in a string it works fine:

xmlFullPath = '$_docsDir$xmlRelativePath'

Really scratching my head here. Is there something obvious I am missing ?

Thanks in advance.


Solution

  • path.join does not just concatenate strings. Your last argument starts with a path separator and is treated as an absolute path (despite your desire to treat it as a relative path), so it will override all the previous arguments. This is explained in the path.join documentation:

    If a part is an absolute path, then anything before that will be ignored:

    p.join('path', '/to', 'foo'); // -> '/to/foo'
    

    Either change xmlRelativePath to not start with a directory separator or, instead of using path.join, use a normal string concatenation followed by path.normalize:

    xmlFullPath = path.normalize(['ARRRRGGG', docsDir, xmlRelativePath].join('/'));
    

    (Because you're using XML paths, I'm using '/' directly as the directory separator.)