예제 #1
0
def gen(page_name, param):
    # pprint(param)
    src = os.path.join(kordir.template, 'page.dart')
    code = open(src).read()
    result = code.replace("{{page_name}}", utils.class_case(page_name))
    filename = page_name + '.dart'
    dst = os.path.join('lib', 'pages', filename)
    with open(dst, "w") as text_file:
        text_file.write(result)
예제 #2
0
def create_file(model_name, attributes):
    model = utils.class_case(model_name)
    out = "class %s {\n" % model
    atts = flutter_utils.get_attribute_list(attributes)
    utils.save_model(model_name, atts)
    for att in atts:
        out += f"  {att['type']} _{att['name']};\n"

    # constructor, has comma delim except the last one
    # out += f"\n  {model}("
    # for att in atts[:-1]:
    #     out += f"this._{att['name']}, "
    # out += f"this._{atts[-1]['name']}"
    # out += ");\n\n"
    # getter

    out += f"\n  {model}();\n"

    for att in atts:
        out += f"  {att['type']} get {att['name']} => _{att['name']};\n"
    out += "\n"
    # setter
    for att in atts:
        out += f"  set {att['name']}({att['type']} {att['name']}) " + "{ "
        out += f"this._{att['name']} = {att['name']}; " + "}\n"
    out += "\n"
    # toMap
    out += "  Map<String, dynamic> toMap() {\n"
    out += "    var map = Map<String, dynamic>();\n"
    out += "    if (id != null) {\n"
    out += "      map['id'] = _id;\n"
    out += "    }\n"
    for att in atts:
        if att['name'] == 'id':
            continue
        out += f"    map['{att['name']}'] = _{att['name']};\n"
    out += "    return map;\n"
    out += "  }\n"
    out += "\n"
    # fromMap
    out += f"  {model}.fromMap( Map<String, dynamic> map) " + "{\n"
    for att in atts:
        out += f"    this._{att['name']} = map['{att['name']}'];\n"
    out += "  }\n}\n"

    # done, output to file
    filename = stringcase.lowercase(model) + '.dart'
    dst = os.path.join('lib', 'models', filename)
    with open(dst, "w") as text_file:
        text_file.write(out)
예제 #3
0
def gen(page_name, param):
    page_class = utils.class_case(page_name)
    app_param = utils.get_app_param()
    app_name = app_param['app_name']
    try:
        branch = param['node']['@TEXT']
        if branch.startswith('model:'):
            model = branch.split(':')[1]
            model = model.lstrip()
        else:
            model = ''
    except Exception:
        model = ''
    if model == '':
        print("!!! view page require `model: ` branch")
        return
    model_class = utils.class_case(model)
    atts = page_utils.get_model(model)
    out = \
        f'''
{utils.WARNING}
import 'package:flutter/material.dart';
import 'package:{app_name}/models/ccard.dart';
import 'package:{app_name}/models/ccard_db.dart';
import 'package:{app_name}/pages/text_style.dart';

class {page_class}Page extends StatelessWidget {{
  {page_class}Page(this.context, this.{model}, this.editCard);

  final {model_class}DatabaseHelper db = {model_class}DatabaseHelper();
  final BuildContext context;
  final {model_class} {model};
  final Function editCard;
  final double titleWidth = 132.0;

  @override
  Widget build(BuildContext context) {{
    return Scaffold(
      appBar: AppBar(
        title: Text('View {model_class} ${{this.{model}.id}}'),
      ),
      body: Padding(
        child: viewCard(),
        padding: EdgeInsets.only(top: 15.0, left: 10.0, right: 10.0),
      ),
    );
  }}

  Widget viewCard() {{
    return ListView(
      children: <Widget>[
'''
    for att in atts:
        if att['name'] in ['id', 'createdAt']:
            continue
        out += f"        rowItem('{stringcase.titlecase(att['name'])}', this.{model}.{att['name']}),\n"
    out += \
        f'''
        buttons(),
      ],
    );
  }}

  Widget buttons() {{
    return Padding(
      padding: EdgeInsets.only(top: 15.0, bottom: 15.0),
      child: Row(
        children: <Widget>[
          Expanded(
            child: RaisedButton(
              color: Theme.of(context).primaryColorDark,
              textColor: Colors.white,
              child: Text(
                'Edit',
                textScaleFactor: 1.5,
              ),
              onPressed: () {{
                editCard(this.{model});
              }},
            ),
          ),
          Container(
            width: 5.0,
          ),
          Expanded(
            child: RaisedButton(
                color: Colors.red[900],
                textColor: Colors.white,
                child: Text(
                  'Delete',
                  textScaleFactor: 1.5,
                ),
                onPressed: () => delete()),
          ),
        ],
      ),
    );
  }}

  Widget rowItem(label, item) {{
    return Row(children: <Widget>[
      SizedBox(
        width: titleWidth,
        child: Text(
          label,
          style: Style.title,
        ),
      ),
      Expanded(
        child: Text(item.toString(), style: Style.content),
      ),
    ]);
  }}

  void delete() {{
    showDialog(
        context: context,
        builder: (BuildContext context) {{
          return AlertDialog(
            title: Text('WARNING'),
            content: Text('Are you sure you want to delete this record?'),
            actions: <Widget>[
              FlatButton(
                child: Text('Yes'),
                onPressed: () {{
                  db.delete{model_class}(this.{model}.id).then((value) {{
                    Navigator.popUntil(context,
                        ModalRoute.withName(Navigator.defaultRouteName));
                  }});
                }},
              ),
              FlatButton(
                child: Text('Cancel'),
                onPressed: () {{
                  Navigator.of(context).pop();
                }},
              )
            ],
          );
        }});
  }}
}}



'''

    filename = page_name + '.dart'
    dst = os.path.join('lib', 'pages', filename)
    with open(dst, "w") as text_file:
        text_file.write(out)
    return True
예제 #4
0
def gen(page_name, param):
    page_class = utils.class_case(page_name)
    app_param = utils.get_app_param()
    app_name = app_param['app_name']
    # pprint(pages)
    model = ''
    displays = []
    for node in param['node']:
        if node['@TEXT'].startswith('model:'):
            model = node['@TEXT'].split(':')[1]
            model = model.lstrip()
        if node['@TEXT'].startswith('fab:'):
            fab_page = node['@TEXT'].split(':')[1]
            fab_page = fab_page.lstrip()
        if node['@TEXT'].lower().startswith('onpressed:'):
            onpressed_page = node['@TEXT'].split(':')[1]
            onpressed_page = onpressed_page.lstrip()
        if node['@TEXT'].lower().startswith('display'):
            for display in node['node']:
                displays.append(display['@TEXT'])
    if model == '':
        print("!!! home page require `model: ` branch")
        return
    model_class = utils.class_case(model)
    fab_page_class = utils.class_case(fab_page)
    onpressed_page_class = utils.class_case(onpressed_page)
    out = \
f'''
import 'package:flutter/material.dart';
import 'package:{app_name}/models/ccard.dart';
import 'package:{app_name}/theme.dart' as Theme;

class CardRow extends StatelessWidget {{
  final {model_class} {model};
  final Function viewCard;

  CardRow(this.{model}, this.viewCard);

  @override
  Widget build(BuildContext context) {{
    final {model}Card = new Container(
      margin: const EdgeInsets.only(left: 8.0, right: 8.0),
      decoration: new BoxDecoration(
        color: Theme.Colors.ccardCard,
        shape: BoxShape.rectangle,
        borderRadius: new BorderRadius.circular(8.0),
        boxShadow: <BoxShadow>[
          new BoxShadow(
              color: Colors.black,
              blurRadius: 10.0,
              offset: new Offset(0.0, 10.0))
        ],
      ),
      child: new Container(
        margin: const EdgeInsets.only(top: 16.0, left: 128.0),
        constraints: new BoxConstraints.expand(),
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
'''
    for display in displays:
        out += f"            new Text({model}.{display}, style: Theme.TextStyles.planetTitle),\n"
    out += \
f'''
          ],
        ),
      ),
    );

    return new Container(
      height: 120.0,
      margin: const EdgeInsets.only(top: 16.0, bottom: 8.0),
      child: new FlatButton(
        onPressed: () => viewCard({model}),
        child: new Stack(
          children: <Widget>[
            {model}Card,
          ],
        ),
      ),
    );
  }}

}}
'''

    filename = model + '_row' + '.dart'
    dst = os.path.join('lib', 'pages', filename)
    with open(dst, "w") as text_file:
        text_file.write(out)
    return True
예제 #5
0
def create_file(model_name, attributes):
    app_param = utils.get_app_param()
    app_name = app_param['app_name']
    model = utils.class_case(model_name)
    model_file = stringcase.lowercase(model_name)
    model_var = stringcase.lowercase(model[0]) + model[1:]
    atts = flutter_utils.get_attribute_list(attributes)
    out = \
f'''
import 'package:sqflite/sqflite.dart';
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:{app_name}/models/{model_file}.dart';

class {model}DatabaseHelper {{
  static {model}DatabaseHelper _databaseHelper;
  static Database _database;

  String table{model} = '{model_file}';
'''
    for att in atts:
        out += f"  String col{utils.class_case(att['name'])} = '{att['name']}';\n"
    out += \
f'''
  {model}DatabaseHelper._createInstance();

  factory {model}DatabaseHelper() {{
    if (_databaseHelper == null) {{
      _databaseHelper = {model}DatabaseHelper._createInstance();
    }}
    return _databaseHelper;
  }}

  Future<Database> get database async {{
    if (_database == null) {{
      _database = await init();
    }}
    return _database;
  }}

  Future<Database> init() async {{
    Directory dir = await getApplicationDocumentsDirectory();
    String path = dir.path + '{app_name}.db';
    var db = await openDatabase(path, version: 1, onCreate: _createDatabase);
    return db;
  }}

  void _createDatabase(Database db, int version) async {{
    await db.execute('CREATE TABLE $table{model}('
      '$colId INTEGER PRIMARY KEY AUTOINCREMENT, '
'''
    db_types = {
        'string': 'TEXT',
        'int': 'INTEGER',
        'bool': 'INTEGER',
        'double': 'REAL'
    }
    for att in atts[:-1]:
        att_name = utils.class_case(att['name'])
        if att_name == 'Id':
            continue
        out += f"      '$col{att_name} {db_types[att['type'].lower()]}, '\n"
    att = atts[-1]
    out += f"      '$col{utils.class_case(att['name'])} {db_types[att['type'].lower()]} ) '\n"
    out += "    );\n"
    out += \
f'''
  }}

  Future<{model}> get{model}(int id) async {{
    Database db = await this.database;
    var result = await db.query(table{model}, where: '$colId = ?',
      whereArgs: [id]);
    return {model}.fromMap(result[0]);
  }}

  Future<List<Map<String, dynamic>>> get{model}s() async {{
    Database db = await this.database;
    var result = await db.query(table{model});
    return result;
  }}

  Future<int> insert{model}({model} {model_var}) async {{
    Database db = await this.database;
    var result = await db.insert(table{model}, {model_var}.toMap());
    return result;
  }}

  Future<int> update{model}({model} {model_var}) async {{
    Database db = await this.database;
    var result = await db.update(table{model}, {model_var}.toMap(), where: '$colId = ?',
      whereArgs: [{model_var}.id]);
    return result;
  }}

  Future<int> delete{model}(int id) async {{
    Database db = await this.database;
    int result = await db.delete(table{model}, where: '$colId = ?',
      whereArgs: [id]);
    return result;
  }}

  Future<int> getCount() async {{
    Database db = await this.database;
    List<Map<String, dynamic>> x = await db.rawQuery('SELECT COUNT(*) FROM $table{model}');
    int result = Sqflite.firstIntValue(x);
    return result;
  }}

  Future<List<{model}>> get{model}List() async {{

  var {model_var}MapList = await get{model}s();
  int count = {model_var}MapList.length;

  List<{model}> {model_var}List = List<{model}>();
  for (int i = 0; i < count; i++) {{
    {model_var}List.add({model}.fromMap({model_var}MapList[i]));
  }}

  return {model_var}List;
}}


}}
'''

    # done, output to file
    filename = stringcase.lowercase(model) + '_db.dart'
    dst = os.path.join('lib', 'models', filename)
    with open(dst, "w") as text_file:
        text_file.write(out)
예제 #6
0
def gen(page_name, param):
    page_class = utils.class_case(page_name)
    app_param = utils.get_app_param()
    app_name = app_param['app_name']
    try:
        branch = param['node']['@TEXT']
        if branch.startswith('model:'):
            model = branch.split(':')[1]
            model = model.lstrip()
        else:
            model = ''
    except Exception:
        model = ''
    if model == '':
        print("!!! edit page require `model: ` branch")
        return
    model_class = utils.class_case(model)
    atts = page_utils.get_model(model)
    out = \
        f'''
{utils.WARNING}

import 'package:flutter/material.dart';
import 'package:{app_name}/models/{model}.dart';
import 'package:{app_name}/models/{model}_db.dart';
// import 'package:intl/intl.dart';

class {page_class}Page extends StatefulWidget {{
  {page_class}Page(this.{model});

  final {model_class} {model};

  @override
  State<StatefulWidget> createState() {{
    return _{page_class}Page(this.{model});
  }}
}}

class _{page_class}Page extends State<{page_class}Page> {{
  _{page_class}Page(this.{model});

  {model_class}DatabaseHelper db = {model_class}DatabaseHelper();

  String appBarTitle = "Edit";
  {model_class} {model};
'''
    for att in atts:
        if att['name'] in ['id', 'createdAt']:
            continue
        out += f"  TextEditingController {att['name']}Controller = TextEditingController();\n"
    out += \
        f'''

  @override
  void initState() {{

'''
    for att in atts:
        if att['name'] in ['id', 'createdAt']:
            continue
        if att['type'] == 'String':
            out += f"    {att['name']}Controller.text = {model}.{att['name']};\n"
        else:
            out += f"    {att['name']}Controller.text = {model}.{att['name']}.toString();\n"
    out += \
        f'''
  }}

  @override
  Widget build(BuildContext context) {{

    return WillPopScope(
        onWillPop: () {{
          moveToLastScreen();
        }},
        child: Scaffold(
          appBar: AppBar(
            title: Text(appBarTitle),
            leading: IconButton(
                icon: Icon(Icons.arrow_back),
                onPressed: () {{
                  moveToLastScreen();
                }}),
          ),
          body: Padding(
            padding: EdgeInsets.only(top: 15.0, left: 10.0, right: 10.0),
            child: ListView(
              children: <Widget>[

'''
    keyboard_type = {'String': 'text', 'int': 'number', 'double': 'number'}

    for att in atts:
        if att['name'] in ['id', 'createdAt']:
            continue
        out += f"                rowItem('{stringcase.titlecase(att['name'])}', {att['name']}Controller, '{keyboard_type[att['type']]}'),\n"
    out += \
        f'''
                buttons(),
              ],
            ),
          ),
        ));
  }}

  Widget buttons() {{
    return Padding(
      padding: EdgeInsets.only(top: 15.0, bottom: 15.0),
      child: Row(
        children: <Widget>[
          Expanded(
            child: RaisedButton(
              color: Theme.of(context).primaryColorDark,
              textColor: Theme.of(context).primaryColorLight,
              child: Text(
                'Save',
                textScaleFactor: 1.5,
              ),
              onPressed: () {{
                setState(() {{
                  // debugPrint("Save button clicked");
                  _save();
                }});
              }},
            ),
          ),
          Container(
            width: 5.0,
          ),
          Expanded(
            child: RaisedButton(
              color: Theme.of(context).primaryColorDark,
              textColor: Theme.of(context).primaryColorLight,
              child: Text(
                'Cancel',
                textScaleFactor: 1.5,
              ),
              onPressed: () {{
                setState(() {{
                  Navigator.pop(context, false);
                }});
              }},
            ),
          ),
        ],
      ),
    );
  }}

  Widget rowItem(label, controller, keyboard) {{
    TextStyle textStyle = Theme.of(context).textTheme.title;
    return Padding(
      padding: EdgeInsets.only(top: 15.0, bottom: 15.0),
      child: TextField(
        controller: controller,
        keyboardType: keyboard=='number'
            ? TextInputType.number
            : TextInputType.text,
        onChanged: null,
        style: textStyle,
        decoration: InputDecoration(
            labelText: label,
            labelStyle: textStyle,
            border:
                OutlineInputBorder(borderRadius: BorderRadius.circular(5.0))),
      ),
    );
  }}

  void moveToLastScreen() {{
    Navigator.pop(context, false);
  }}

  void _save() async {{
'''
    for att in atts:
        if att['name'] in ['id', 'createdAt']:
            continue
        if att['type'] == 'String':
            out += f"    {model}.{att['name']} = {att['name']}Controller.text;\n"
        else:
            out += f"    {model}.{att['name']} = {att['type']}.tryParse({att['name']}Controller.text);\n"
    out += \
        f'''

    ccard.createdAt = DateTime.now().toIso8601String();
    await db.updateCcard(ccard);
    Navigator.pop(context, true);
  }}
}}

'''

    filename = page_name + '.dart'
    dst = os.path.join('lib', 'pages', filename)
    with open(dst, "w") as text_file:
        text_file.write(out)
    return True
예제 #7
0
def gen(page_name, param, pages):
    page_class = utils.class_case(page_name)
    app_param = utils.get_app_param()
    app_name = app_param['app_name']
    # pprint(pages)
    model = ''
    for node in param['node']:
        if node['@TEXT'].startswith('model:'):
            model = node['@TEXT'].split(':')[1]
            model = model.lstrip()
        if node['@TEXT'].startswith('fab:'):
            fab_page = node['@TEXT'].split(':')[1]
            fab_page = fab_page.lstrip()
        if node['@TEXT'].lower().startswith('onpressed:'):
            onpressed_page = node['@TEXT'].split(':')[1]
            onpressed_page = onpressed_page.lstrip()
    if model == '':
        print("!!! home page require `model: ` branch")
        return False
    model_class = utils.class_case(model)
    fab_page_class = utils.class_case(fab_page)
    onpressed_page_class = utils.class_case(onpressed_page)
    out = \
f'''
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:{app_name}/theme.dart' as Theme;
import 'package:{app_name}/models/ccard.dart';
import 'package:{app_name}/models/{model}_db.dart';
import 'package:{app_name}/pages/{model}_row.dart';
'''
    for page in pages:
        if page != 'home':
            out += f"import 'package:{app_name}/pages/{page}.dart';\n"
    out += \
f'''

class {page_class}Page extends StatefulWidget {{
  {page_class}Page({{Key key, this.title}}) : super(key: key);
  final String title;

  @override
  _{page_class}Page createState() => _{page_class}Page();
}}

class _{page_class}Page extends State<{page_class}Page> {{
  BuildContext context;
  {model_class}DatabaseHelper dbHelper = {model_class}DatabaseHelper();
  List<{model_class}> {model}s;
  int count = 0;

  void updateCardView() {{
    final Future<Database> dbFuture = dbHelper.init();
    dbFuture.then((database) {{
      Future<List<{model_class}>> listFuture = dbHelper.get{model_class}List();
      listFuture.then(({model}s) {{
        setState(() {{
          this.{model}s = {model}s;
          this.count = {model}s.length;
        }});
      }});
    }});
  }}

  void _new() {{
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) =>
                {fab_page_class}Page())).then((value) {{
      setState(() => updateCardView());
    }});
  }}

  void viewCard({model_class} card) {{
    Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => {onpressed_page_class}Page(context, card, editCard)))
        .then((value) {{
      setState(() => updateCardView());
    }});
  }}

  void editCard({model_class} card) {{
    Navigator.push(
            context, MaterialPageRoute(builder: (context) => EditPage(card)))
        .then((value) {{
      if (value) {{
        setState(() {{
          updateCardView();
          _showAlertDialog('Status', 'Updated Successfully');
        }});
      }}
    }});
  }}

  void _showAlertDialog(String title, String message) {{
    AlertDialog alertDialog = AlertDialog(
      title: Text(title),
      content: Text(message),
    );
    showDialog(context: context, builder: (_) => alertDialog);
  }}

  @override
  Widget build(BuildContext context) {{
    if ({model}s == null) {{
      {model}s = List<{model_class}>();
      updateCardView();
    }}
    this.context = context;
    return Scaffold(
      appBar: AppBar(
        leading: Icon(Icons.filter_tilt_shift),
        title: Text(widget.title),
      ),
      body: homeBody(),
      backgroundColor: Theme.Colors.planetPageBackground,
      floatingActionButton: FloatingActionButton(
        onPressed: _new,
        tooltip: 'Add new',
        backgroundColor: Theme.Colors.appBarDetailBackground,
        child: Icon(Icons.add),
      ),
    );
  }}

  Widget homeBody() {{
    return ListView.builder(
      itemExtent: 160.0,
      itemCount: this.{model}s.length,
      itemBuilder: (_, index) => new CardRow(this.{model}s[index], viewCard),
    );
  }}
}}

'''

    filename = page_name+'.dart'
    dst = os.path.join('lib','pages',filename)
    with open(dst, "w") as text_file:
        text_file.write(out)
    return True