Home > Software engineering >  How to format Dart code programmatically using Dart?
How to format Dart code programmatically using Dart?

Time:12-17

We can format dart code using the command line tool dart format .:

https://dart.dev/tools/dart-format

But can you format dart code programmatically using dart code?

Is there something like DartFormater.format(str);?

CodePudding user response:

The dart format command line tool uses the dart_style package.

You can add the package as a dependency in your pubspec.yaml.

dependencies:
  dart_style: ^2.2.4

You can use the formatter in your code like so:

import 'package:dart_style/dart_style.dart';

const String str = '''
void    main( )   {  
      print
      ('hello world!'
      );
   }
''';

void main() {
  print(DartFormatter().format(str));
}

This will print out the formatted string below:

void main() {
  print('hello world!');
}
  • Related