dartpoet 1.0.3+2

  • Readme
  • Changelog
  • Example
  • Installing
  • 72

You can use this library to programmatically generate dart file. Like Javapoet.

Usage #

A simple usage example:

import 'package:dartpoet/dartpoet.dart';

main() {
  // define a file spec
  FileSpec fileSpec = FileSpec.build(
    dependencies: [
      DependencySpec.import('dart:convert'),
    ],
    // define methods in this file
    methods: [
      // define method1
      MethodSpec.build(
        'globalFunc1',
        // define parameters in this method
        parameters: [
          ParameterSpec.normal('param1', type: TypeToken.ofInt()),
        ],
        // define code block spec in this method
        codeBlock: CodeBlockSpec.line('print(\'hello world!\');'),
      ),
    ],
    classes: [
      ClassSpec.build(
        'Student',
        properties: [
          PropertySpec.ofString('name'),
          PropertySpec.ofInt('score'),
        ],
        constructorBuilder: (owner) sync* {
          yield ConstructorSpec.normal(
            owner,
            parameters: [
              ParameterSpec.normal('name', isSelfParameter: true, type: TypeToken.ofString()),
              ParameterSpec.normal('score', isSelfParameter: true, type: TypeToken.ofInt()),
            ],
          );
        },
        doc: DocSpec.text('this is a student class'),
      ),
      ClassSpec.build(
        'HelloWorld',
        metas: [MetaSpec.of('Object()')],
        doc: DocSpec.text('hello! world!.'),
        superClass: TypeToken.of(Object),
        methods: [
          MethodSpec.build('sayHello', codeBlock: CodeBlockSpec.line('print(\'hello\');')),
        ],
        properties: [
          PropertySpec.of('students', type: TypeToken.ofListByToken(TypeToken.ofName('Student')), defaultValue: []),
          PropertySpec.of('studentScores', defaultValue: {'John': 100, 'Rek': 50}, type: TypeToken.ofMap<String, int>()),
          PropertySpec.of('run', type: TypeToken.ofBool()),
        ],
        getters: [
          GetterSpec.build('studentCount', type: TypeToken.ofInt(), codeBlock: CodeBlockSpec.lines(['students.length;'])),
        ],
        setters: [
          SetterSpec.build('newStudent', ParameterSpec.normal('student', type: TypeToken.ofName('Student')),
              codeBlock: CodeBlockSpec.line('students.add(student);'))
        ],
      ),
    ],
  );

  // define a dart file
  DartFile dartFile = DartFile.fromFileSpec(fileSpec);
  // output file content
  print(dartFile.outputContent());
  dartFile.outputSync('./example/example_output.dart');
}

Output #

The sample code generate a file at ./example/example_output.dart


import 'dart:convert';

/// this is a student class
class Student {
  String name;
  int score;

  Student(this.name, this.score);
}

/// hello! world!.
@Object()
class HelloWorld extends Object {
  List<Student> students=[];
  Map<String, int> studentScores={"John":100,"Rek":50};
  bool run;

  int get studentCount  => students.length;

  set newStudent(Student student) => students.add(student);

  sayHello()  => print('hello');
}


globalFunc1(int param1)  => print('hello world!');

Features and bugs #

Please file feature requests and bugs at the issue tracker.

1.0.0 #

  • Initial version, created by Stagehand

1.0.1 #

  • fixed TypeToken, now can use '==' operator to compare two TypeToken

1.0.2 #

  • remove dart_format.dart and replace with package:dart_style

1.0.2+1 #

  • bug fixed

1.0.2+2 #

  • bug fixed

1.0.3 #

  • New constructor of MetaSpec
    • MetaSpec.ofInstance(String instanceName)
    • MetaSpec.ofConstructor(TypeToken type, {List<ParameterSpec> parameters})

example/dartpoet_example.dart

import 'package:dartpoet/dartpoet.dart';

main() {
  // define a file spec
  FileSpec fileSpec = FileSpec.build(
    dependencies: [
      DependencySpec.import('dart:convert'),
    ],
    // define methods in this file
    methods: [
      // define method1
      MethodSpec.build(
        'globalFunc1',
        // define parameters in this method
        parameters: [
          ParameterSpec.normal('param1', type: TypeToken.ofInt()),
        ],
        // define code block spec in this method
        codeBlock: CodeBlockSpec.line('print(\'hello world!\');'),
      ),
    ],
    classes: [
      ClassSpec.build(
        'Student',
        properties: [
          PropertySpec.ofString('name'),
          PropertySpec.ofInt('score'),
        ],
        constructorBuilder: (owner) sync* {
          yield ConstructorSpec.normal(
            owner,
            parameters: [
              ParameterSpec.normal('name', isSelfParameter: true, type: TypeToken.ofString()),
              ParameterSpec.normal('score', isSelfParameter: true, type: TypeToken.ofInt()),
            ],
          );
        },
        doc: DocSpec.text('this is a student class'),
      ),
      ClassSpec.build(
        'HelloWorld',
        metas: [
          MetaSpec.ofConstructor(TypeToken.ofName("Object")),
          MetaSpec.ofInstance("deprecated"),
          MetaSpec.ofConstructor(TypeToken.ofName("JsonKey"), parameters: [
            ParameterSpec.named("ignored", isValue: true, value: false),
            ParameterSpec.normal("p1", isValue: true, value: "aa1234"),
          ]),
        ],
        doc: DocSpec.text('hello! world!.'),
        superClass: TypeToken.of(Object),
        methods: [
          MethodSpec.build('sayHello', codeBlock: CodeBlockSpec.line('print(\'hello\');')),
        ],
        properties: [
          PropertySpec.of('students', type: TypeToken.ofListByToken(TypeToken.ofName('Student')), defaultValue: []),
          PropertySpec.of('studentScores', defaultValue: {'John': 100, 'Rek': 50}, type: TypeToken.ofMap<String, int>()),
          PropertySpec.of('run', type: TypeToken.ofBool()),
        ],
        getters: [
          GetterSpec.build('studentCount', type: TypeToken.ofInt(), codeBlock: CodeBlockSpec.lines(['students.length;'])),
        ],
        setters: [
          SetterSpec.build('newStudent', ParameterSpec.normal('student', type: TypeToken.ofName('Student')),
              codeBlock: CodeBlockSpec.line('students.add(student);'))
        ],
      ),
    ],
  );

  // define a dart file
  DartFile dartFile = DartFile.fromFileSpec(fileSpec);
  // output file content
  print(dartFile.outputContent());
  dartFile.outputSync('./example/example_output.dart');
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  dartpoet: ^1.0.3+2

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:dartpoet/dartpoet.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
45
Health:
Code health derived from static analysis. [more]
99
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
72
Learn more about scoring.

We analyzed this package on Oct 21, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.5.1
  • pana: 0.12.21

Platforms

Detected platforms: Flutter, other

Primary library: package:dartpoet/dartpoet.dart with components: io.

Health issues and suggestions

Document public APIs. (-0.78 points)

266 out of 268 API elements have no dartdoc comment.Providing good documentation for libraries, classes, functions, and other API elements improves code readability and helps developers find and use your API.

Fix lib/src/spec.dart. (-0.50 points)

Analysis of lib/src/spec.dart reported 1 hint:

line 1 col 8: Unused import: 'package:dartpoet/dartpoet.dart'.

Format lib/src/class_spec.dart.

Run dartfmt to format lib/src/class_spec.dart.

Format lib/src/code_block_spec.dart.

Run dartfmt to format lib/src/code_block_spec.dart.

Fix additional 6 files with analysis or formatting issues.

Additional issues in the following files:

  • lib/src/dart_file.dart (Run dartfmt to format lib/src/dart_file.dart.)
  • lib/src/file_spec.dart (Run dartfmt to format lib/src/file_spec.dart.)
  • lib/src/parameter_spec.dart (Run dartfmt to format lib/src/parameter_spec.dart.)
  • lib/src/property_spec.dart (Run dartfmt to format lib/src/property_spec.dart.)
  • lib/src/setter_getter_spec.dart (Run dartfmt to format lib/src/setter_getter_spec.dart.)
  • lib/src/type_token.dart (Run dartfmt to format lib/src/type_token.dart.)

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.2.0 <3.0.0
dart_style ^1.2.10 1.3.2
path ^1.4.1 1.6.4
xfile ^1.0.2 1.0.2
Transitive dependencies
analyzer 0.38.5 0.39.0
args 1.5.2
async 2.4.0
charcode 1.1.2
collection 1.14.12
convert 2.1.1
crypto 2.1.3
csslib 0.16.1
front_end 0.1.27 0.1.28
glob 1.2.0
html 0.14.0+3
js 0.6.1+1
kernel 0.3.27 0.3.28
meta 1.1.7
node_interop 1.0.3
node_io 1.0.1+2
package_config 1.1.0
pub_semver 1.4.2
source_span 1.5.5
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6
watcher 0.9.7+12
yaml 2.2.0
Dev dependencies
pedantic ^1.0.0 1.8.0+1
test ^1.0.0