Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format Dart code programmatically using Dart?

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);?

like image 292
normidar Avatar asked Jun 16 '26 15:06

normidar


1 Answers

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!');
}
like image 122
mmcdon20 Avatar answered Jun 20 '26 18:06

mmcdon20



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!