Provides API to generate Dart source code

  API

DartWriter

DartWriter provides API to generate Dart source code. It can make your job easier while developing flutter/dart tools. You can also generate Flutter UI code.

Hello World Example

var context = EditorContext(enableDartFormatter: true);
var code = Method(
  name: 'main',
  returnType: 'void',
  statements: [
    Call('print',
      argument: Argument([
        ArgumentItem("'Hello World!'")
      ])
    ),
    Return('0')
  ]
);
print(context.build([code]));

Generated as below:

void main() {
  print('Hello World!');
  return 0;
}

Flutter Stateless Widget Example

Input

{
  "as": "Scaffold",
  "appBar": {
    "as": "AppBar",
    "title": {
      "as": "Text",
      "params": [
        "'Ahmet'"
      ]
    },
    "centerTitle": "false"
  },
  "body": {
    "as": "Center",
    "child": {
      "as": "Row",
      "children": [
        {
          "as": "Icon",
          "params": ["Icons.add"],
          "color": "Colors.red"
        },
        {
          "as": "Text",
          "params": ["'Ahmet'"],
          "textAlign": "TextAlign.center"
        }
      ]
    }
  }
}

Code:

var context = EditorContext(enableDartFormatter: true);
var dartHelper = DartHelper.instance;
Map map = jsonDecode(json);

var homePage = Class('HomePage',
  baseClass: 'StatelessWidget',
  methods: [
    Annotation('override'),
    Method(
      name: 'build',
      returnType: 'Widget',
      param: Parameter([
        ParameterItem('BuildContext context'),
      ]),
      statements: [ Return(dartHelper.getCodeFromMap(map)) ]
    )
  ]
);

print(context.build([
  Import('package:flutter/material.dart'),
  homePage
]));

Generated ui code:

import 'package:flutter/material.dart';

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Ahmet'), centerTitle: false),
        body: Center(
            child: Row(children: [
          Icon(Icons.add, color: Colors.red),
          Text('Ahmet', textAlign: TextAlign.center)
        ])));
  }
}

Installation

In the pubspec.yaml of your Flutter / Dart project, add the following dependency:

dependencies:
  ...
  dart_writer: any

In your library file add the following import:

import 'package:dart_writer/dart_writer.dart';

API Documentation

Conditions

Method(
  name: 'getMin',
  returnType: 'int',
  statements: [
    Assign('var num1', '5'),
    Assign('var num2', '10'),
    If(condition: 'num1 < num2', statements: [Return('num1')]),
    ElseIf(condition: 'num1 == num2', statements: [Return('num1')]),
    Else(statements: [Return('num2')])
  ]  
)

Generated code:

int getMin() {
  var num1 = 5;
  var num2 = 10;
  if (num1 < num2) {
    return num1;
  } else if (num1 == num2) {
    return num1;
  } else {
    return num2;
  }
}

Loops

Method(
  name: 'loops',
  returnType: 'void',
  statements: [
    For('i = 0', 'i < 5', 'i++',
      statements: [RawCode('print(i);')]
    ),
    ForEach('item', 'userList',
      statements: [
        Return('UserCard(item)')
      ]
    ),
    While('i < 5',
      statements: [ RawCode('print(i);'), Assign('i', 'i + 1')]
    )
  ]  
)

Generated code:

void loops() {
  for (var i = 0; i < 5; i++) {
    print(i);
  }
  for (var item in userList) { 
    return UserCard(item);     
  }
  while (i < 5) {
    print(i);
    i = i + 1;
  }
}

Statements

Method(name: 'do', returnType: 'int',
  statements: [
    Assign('var i', '5'),
    Assign('var name', Call('getName')),
    Return('i')
  ] 
)

Generated code:

int do() {
  var i = 5;
  var name = getName();
  return i;
}

OOP Concepts

Class

ParameterDescriptionOutput
String classNameClass Nameclass Bird
bool isAbstract?Generating abstract class if value is trueabstract class Animal or class Animal
List<Constructors>?more than one constructor can be definedSingleton._init() , Singleton({this.a}) : super(a)
String? baseClassextends to base classclass Bird extends Animal
List<String>? mixinsindicates the use of mixinsclass Bird with Feather, Walk
List<String>? interfacesimplements interfaceclass Bird implements Flyable, Crowable
List<Attribute>? attributes;attributes of classfinal String name;
List<IExpression>? methods;all methods of class such as Method, Getters, Setttersfinal String name;

Constructor

ParameterDescriptionOutput
String classNameClass Nameclass Singleton
String consturctorName?if value is null Default constructor. if not value, named constructor.Singleton._init() , Singleton({this.a})
Parameter? paramConstructor parametersSingleton({required this.a})Singleton(this.a, {this.b})
String? superArgumentcall constructor of base classSingleton(this.a) : super(a)
String? modifiermodifier of constructor such as factoryfactory Singleton()

Attribute

ParameterDescriptionOutput
String nameAttribute Namename
String typeAttribute typeString name
String? modifiersAttribute modifiersfinal String name
String? valueinitialize value to attributefinal String name = 'Ahmet'

Methods

Method

ParameterDescriptionOutput
String nameMethod Namewalk
String returnType?Return typevoid walk
Parameter? paramMethod parametersvoid walk({required int step})
bool? isAsyncis async method?void walk({required int step}) async {}
String? modifierModifier of method such as staticstatic void walk
List<IExpression>? statementsbody of method.Code here...

Getter

ParameterDescriptionOutput
String nameGetter Nameget walk
String returnType?Return typevoid get walk
String? modifierModifier of method such as staticstatic void get name
List<IExpression>? statementsbody of method.Code here...

Setter

ParameterDescriptionOutput
String nameGetter Nameset name
String param?Return typeset name(String name)
List<IExpression>? statementsbody of method.Code here...

Example Class Code:

Class(
  'Bird',
  baseClass: 'Animal',
  interfaces: ['Flyable', 'Crowable'],
  mixins: ['Feather', 'Walk'],
  attributes: <Attribute> [
    Attribute(modifiers: 'final', type: 'String', name: 'name'),
  ],
  constructors: <Constructor> [
    Constructor(
      className: 'Bird',
      constructorName: 'fromName',
      param: Parameter([ParameterItem('this.name', isRequired: true, isNamed: true)]),
        superArgument: Argument([ArgumentItem('name')])
    ),
  ],
  methods: [
    Method(
      name: 'onFly',
      returnType: 'double',
      param: Parameter([ParameterItem('double height')]),
      statements: [Return('height * 2')]
    ),
  ]
);

Generated code:

class Bird extends Animal with Feather, Walk implements Flyable, Crowable {   
  final String name;

  Bird.fromName({required this.name}) : super(name);

  double onFly(double height) {        
    return height * 2;
  }
}

Interface

ParameterDescriptionOutput
String nameInterface Nameinterface Flyable
String? baseClassextends classinterface Flyable extends Breathable
List<IExpression>? prototypesabstract methods of interfacevoid doFly();

Example Interface

Interface('Flyable',
    baseClass: 'Breathable',
    prototypes: [
      Method(name: 'doFly', returnType: 'void')
    ]
)

Generated code:

abstract class Flyable extends Breathable {
  void doFly();
}

Other

ExpressionExample CodeOutput
AnnotationAnnotation(‘override’)@override
ImportImport(‘package:dart_writer/dart_writer.dart’, as: ‘writer’)import 'package:dart_writer/dart_writer.dart' as writer;
EnumEnum(‘Roles’, enums: [‘USER’, ‘ADMIN’, ‘DEVELOPER’])enum Roles { USER, ADMIN, DEVELOPER }
ParamterParameter([ParameterItem(‘String name’, isNamed: true, isRequired: true)]){required String name}
ArgumentArgument([ArgumentItem(“‘Star'”, name:’surname’])surname: 'Star'
RawCodeRawCode(‘var name = user?.name ?? “‘ahmet'”‘)[Output]: var name = user?.name ?? 'ahmet'

Download API to generate Dart source code package source code on GitHub