flutterdart

How to get the File Extension from a string Path


I've got file path saved in variable and I want to get the file type extension by using path package https://pub.dev/packages/path So far I managed to do it by splitting the string like this

final path = "/some/path/to/file/file.dart";
print(path.split(".").last); //prints dart

Is there any way to achieve this with path package?


Solution

  • You can use the extension function in the path package to get the extension from a file path:

    import 'package:path/path.dart' as p;
    
    final path = '/some/path/to/file/file.dart';
    
    final extension = p.extension(path); // '.dart'
    

    If your file has multiple extensions, like file.dart.js, you can specify the optional level parameter:

    final extension = p.extension('file.dart.js', 2); // '.dart.js'