Provides API to generate Dart source code

Overview

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

Parameter Description Output
String className Class Name class Bird
bool isAbstract? Generating abstract class if value is true abstract class Animal or class Animal
List? more than one constructor can be defined Singleton._init() , Singleton({this.a}) : super(a)
String? baseClass extends to base class class Bird extends Animal
List? mixins indicates the use of mixins class Bird with Feather, Walk
List? interfaces implements interface class Bird implements Flyable, Crowable
List? attributes; attributes of class final String name;
List? methods; all methods of class such as Method, Getters, Settters final String name;

Constructor

Parameter Description Output
String className Class Name class Singleton
String consturctorName? if value is null Default constructor. if not value, named constructor. Singleton._init() , Singleton({this.a})
Parameter? param Constructor parameters Singleton({required this.a}), Singleton(this.a, {this.b})
String? superArgument call constructor of base class Singleton(this.a) : super(a)
String? modifier modifier of constructor such as factory factory Singleton()

Attribute

Parameter Description Output
String name Attribute Name name
String type Attribute type String name
String? modifiers Attribute modifiers final String name
String? value initialize value to attribute final String name = 'Ahmet'

Methods

Method

Parameter Description Output
String name Method Name walk
String returnType? Return type void walk
Parameter? param Method parameters void walk({required int step})
bool? isAsync is async method? void walk({required int step}) async {}
String? modifier Modifier of method such as static static void walk
List? statements body of method. Code here...

Getter

Parameter Description Output
String name Getter Name get walk
String returnType? Return type void get walk
String? modifier Modifier of method such as static static void get name
List? statements body of method. Code here...

Setter

Parameter Description Output
String name Getter Name set name
String param? Return type set name(String name)
List? statements body 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

Parameter Description Output
String name Interface Name interface Flyable
String? baseClass extends class interface Flyable extends Breathable
List? prototypes abstract methods of interface void doFly();

Example Interface

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

Generated code:

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

Other

Expression Example Code Output
Annotation Annotation('override') @override
Import Import('package:dart_writer/dart_writer.dart', as: 'writer') import 'package:dart_writer/dart_writer.dart' as writer;
Enum Enum('Roles', enums: ['USER', 'ADMIN', 'DEVELOPER']) enum Roles { USER, ADMIN, DEVELOPER }
Paramter Parameter([ParameterItem('String name', isNamed: true, isRequired: true)]) {required String name}
Argument Argument([ArgumentItem("'Star'", name:'surname']) surname: 'Star'
RawCode RawCode('var name = user?.name ?? "'ahmet'"') [Output]: var name = user?.name ?? 'ahmet'

TASK LIST

  • Unit Tests
You might also like...

VS Code `.code-workspace` file generator

VS Code .code-workspace file generator (for monorepositories with Dart and Flutter projects) TL;DR; Create yaml file config.yaml (check #Format sectio

Feb 18, 2022

Provides Dart Build System builder for creating Injection pattern using annotations.

Provides Dart Build System builder for creating Injection pattern using annotations. Gate generator The core package providing generators using annoat

Dec 20, 2022

Provides simple conversion between Dart classes and Protobuf / Fixnum classes used in gRPC.

grpc_protobuf_convert Provides simple conversion between Dart classes and Protobuf / Fixnum classes used in gRPC. Using the library Add the repo to yo

Nov 1, 2022

A Open Source Dart Library

A Open Source Dart Library

Apr 19, 2022

A simple flexible API wrapper for coinbase commerce API. Totally unofficial.

coinbase_commerce A dart library that connects to interact with the Coinbase Commerce API. Enables projects to connect seamlessly to coinbase and rece

Oct 17, 2021

Provides null-safety implementation to simplify JSON data handling by adding extension method to JSON object

Lazy JSON Provides null-safety implementation to simplify JSON data handling by adding extension method to JSON object and JSON array. Getting started

Oct 27, 2021

A flutter plugin that provides external storage path and external public storage path

ext_storage ext_storage is minimal flutter plugin that provides external storage path and external public storage path

Nov 16, 2021

A flutter package provides controllers and editors for complex models and lists

A flutter package provides controllers and editors for complex models and lists

This package provides controllers and editors for complex models and lists and is inspired by simplicity of TextEditingController. It encapsulates sta

Sep 1, 2022

🚀The Flutter dart code generator from zeplin. ex) Container, Text, Color, TextStyle, ... - Save your time.

🚀The Flutter dart code generator from zeplin. ex) Container, Text, Color, TextStyle, ... - Save your time.

Flutter Gen Zeplin Extension 🚀 The Flutter dart code generator from zeplin. ex) Container, Text, Color, TextStyle, ... - Save your time. ⬇ 1.1k Getti

Oct 12, 2022
Releases(0.0.1)
Owner
Ahmet ÇELİK
Software Engineering Student 3/4
Ahmet ÇELİK
AsyncCallQueue is a Dart class which provides a queuing mechanism to prevent concurrent access to asynchronous code.

async_call_queue AsyncCallQueue is a Dart class which provides a queuing mechanism to prevent concurrent access to asynchronous code. Getting Started

Ron Booth 2 Jan 18, 2022
generate massive amounts of fake data in dart and flutter

generate massive amounts of fake data in Dart & Flutter Faker.dart is a dart port of the famous faker.js package for the web and NodeJS ?? Usage faker

Cas van Luijtelaar 26 Nov 28, 2022
Automatically generate usecase classes from your repository class definition in Dart and Flutter

Repo Case Automatically generate usecase classes from your repository class definition in Dart and Flutter. Check out the official guide on repo_case

Sandro Maglione 5 Jul 30, 2022
Generate random data(string, integer, IPs etc...) using Dart.

Generate random data using Features API provides generation of: Integers in any range of numbers Strings with various characters and length Colors rep

Dinko Pehar 14 Apr 17, 2022
Open source SDK to quickly integrate subscriptions, stop worring about code maintenance, and getting advanced real-time data

Open source SDK to quickly integrate subscriptions, stop worring about code maintenance, and getting advanced real-time data. Javascript / iOS glue framework

glassfy 8 Oct 31, 2022
Converts SVG icons to OTF font and generates Flutter-compatible class. Provides an API and a CLI tool.

Fontify The Fontify package provides an easy way to convert SVG icons to OpenType font and generate Flutter-compatible class that contains identifiers

Igor Kharakhordin 88 Oct 28, 2022
Flutter Cool Random User Generate 🔥🔥

Flutter Cool Random User Generate ????

Hmida 8 Sep 10, 2022
Generate gherkin automated tests

flutter_gherkin_automated Generate gherkin automated tests Preliminary: integration tests performance vs. development Original flutter_gherkin BDD tes

Vladimir E. Koltunov 5 Jul 7, 2022
A simple command-line application to generate simple folder and file structure for Flutter Applications

Kanza_cli is a simple command line tool to generate folder and file structure for your Flutter apps. To use it, you should do the followings: 1. First

Kanan Yusubov 9 Dec 16, 2022
Parse cron string to schedule and generate previous or next schedule item

Parse cron string to schedule and generate previous or next schedule item

Pokhodyun Alexander 2 Apr 17, 2022