Convert Json to Form for Flutter apps

Overview

Convert Json to Form for Flutter apps.

🔥 Star and Share 🔥 the repo to support the project. Thanks!

A flutter plugin to use convert Json to Form

Instalation

  • Add this to your package's pubspec.yaml file:
dependencies:
  json_to_form: "^0.0.1"
  • You can install packages from the command line: with Flutter:
$ flutter packages get

Json to Form V2 Official!!!

  • Import it Now in your Dart code, you can use:
 import 'package:json_to_form/json_schema.dart'; 

JsonSchema

new JsonSchema(
    decorations: decorations,
    form: form,
    onChanged: (dynamic response) {
        this.response = response;
    },
    actionSave: (data) {
        print(data);
    },
    autovalidateMode: AutovalidateMode.always,
    buttonSave: new Container(
        height: 40.0,
        color: Colors.blueAccent,
        child: Center(
            child: Text("Login",style:TextStyle(color: Colors.white,fontWeight: FontWeight.bold)),
        ),
    ),
),

Attribute

  • form (Type String) Your form in String
  • onChanged (Type Function)(1 parameter) call the function every time a change in the form is made
  • padding (Type Double)
  • formMap (Type Map) Your form in Map
  • errorMessages(Type Map) change string for error of required
  • validations(Type Map) to add validation (TextInput,Input, Password, Email or TextArea)
  • decorations(Type Map) to add decoration (TextInput,Input, Password, Email or TextArea)
  • buttonSave(Type Widget) (not RaisedButton problem in onClick)
  • actionSave(Type Function) the function is called when you click on the widget buttonSave
  • autovalidateMode(Type AutovalidateMode) validation type of the form (autovalidate @Deprecated) use this instead

Form

Create Form String

String formString = json.encode({
    'title': 'form example',
    'description':'',
    'fields': [
        ...
    ]
});

Create Form Map

Map formMap = {
    'title': 'form example',
    'description':'',
    'fields': [
        ...
    ]
};

Fields

  • All fields has attribute labelHidden(default false)
  • Important add key for all field for validation required
TextInput or Input

1.- Types?

  • Input
  • Password
  • Email (has default validation)
  • TextArea
  • TextInput
// Example for json string
// to start with a default value you can add the value attribute
  String formString = json.encode({
    'fields': [
        {
             'key': 'inputKey',
             'type': 'Input',
             'label': 'Hi Group',
             'placeholder': "Hi Group flutter",
             'required': true
        },
        {
             'key': 'inputKey',
             'type': 'Input',
             'label': 'Initial Value',
             'value': 'Hello'
             'required': true
        },
    ]
 });
// Example for json Map
// in Map has Attributes validation and decoration

//important to receive 2 parameters in function of Validation
String validationExample(field, value) {
   if (value.isEmpty) {
     return 'Please enter some text';
   }
   return null;
}

Map formMap = {
    'fields': [
        {
                'key': 'inputKey',
                'type': 'Input',
                'label': 'Hi Group',
                'placeholder': "Hi Group flutter",
                'validator': 'digitsOnly',
                'required': true,
                'decoration': InputDecoration(
                          prefixIcon: Icon(Icons.account_box),
                          border: OutlineInputBorder(),
                ),
                'validation':validationExample,
                'keyboardType':TextInputType.number
        },
    ]
 };

1.- How can I place validations for my form String? Excellent :D.

  • In JsonSchema has attributes (validations, decorations)
  • Important that each field has to has its unique key

Map decorations = {
    'inputKey': InputDecoration(
      labelText: "Enter your email",
      prefixIcon: Icon(Icons.account_box),
      border: OutlineInputBorder(),
    ),
  };
  
Map validations = {
    'inputKey': validationExample,
}

dynamic response;
new JsonSchema(
    decorations: decorations,
    validations: validations,
    form: formString,
    onChanged: (dynamic response) {
        this.response = response;
    },
    actionSave: (data) {
        print(data);
    },
    buttonSave: new Container(
        height: 40.0,
        color: Colors.blueAccent,
        child: Center(
            child: Text("Login",style:TextStyle(color: Colors.white,fontWeight: FontWeight.bold)),
        ,
    ),
) 

Radio

 String formString = json.encode({
    'fields': [
         {
                'key': 'radiobutton1',
                'type': 'RadioButton',
                'label': 'Radio Button tests',
                'value': 2,
                'items': [
                  {
                    'label': "product 1",
                    'value': 1,
                  },
                  {
                    'label': "product 2",
                    'value': 2,
                  },
                  {
                    'label': "product 3",
                    'value': 3,
                  }
                ]
         },
    ],
 });

Switch

 String formString = json.encode({
    'fields': [
         {
                 'key': 'switch1',
                 'type': 'Switch',
                 'label': 'Switch test',
                 'value': false,
         },
    ],
 });

Checkbox

 String formString = json.encode({
    'fields': [
        {
                'key': 'checkbox1',
                'type': 'Checkbox',
                'label': 'Checkbox test',
                'items': [
                  {
                    'label': "product 1",
                    'value': true,
                  },
                  {
                    'label': "product 2",
                    'value': false,
                  },
                  {
                    'label': "product 3",
                    'value': false,
                  }
                ]
        }
    ],
 });

Select (New Field)

 String formString = json.encode({
    'fields': [
         {
                 'key': 'select1',
                 'type': 'Select',
                 'label': 'Select test',
                 'value':'product 1',
                 'items': [
                   {
                     'label': "product 1",
                     'value': "product 1",
                   },
                   {
                     'label': "product 2",
                     'value': "product 2",
                   },
                   {
                     'label': "product 3",
                     'value': "product 3",
                   }
                 ]
         }
    ],
 });

when text is added to the TextField, add field called response

// initial form_send_email
[{"type":"Input","label":"Subject","placeholder":"Subject"},{"type":"TextArea","label":"Message","placeholder":"Content"}]

// add text (hi) in TextField Message, update dynamic response; and add field called response
[{type: Input, label: Subject, placeholder: Subject, value: hello}, {type: TextArea, label: Message, placeholder: Content, value: hi }]

Json to Form V1

  • Import it Now in your Dart code, you can use:
 import 'package:json_to_form/json_to_form.dart'; 

Usage

  • TextField
  String form = json.encode([
    {
      'type': 'Input',
      'title': 'Hi Group',
      'placeholder': "Hi Group flutter"
    },
    {
      'type': 'Password',
      'title': 'Password',
    },
    {
      'type': 'Email', 
      'title': 'Email test',
      'placeholder': "hola a todos"
    },
    {
      'type': 'TareaText',
      'title': 'TareaText test',
      'placeholder': "hola a todos"
    },
  ]);
  • Radio
 String form = json.encode([
    {
      'type': 'RadioButton',
      'title': 'Radio Button tests',
      'value': 2,
      'list': [
        {
          'title': "product 1",
          'value': 1,
        },
        {
          'title': "product 2",
          'value': 2,
        },
        {
          'title': "product 3",
          'value': 3,
        }
      ]
    },
  ]);
  • Switch
String form = json.encode([
    {
      'type': 'Switch',
      'title': 'Switch test',
      'switchValue': false,
    },
  ]);
  • Checkbox
String form = json.encode([
    {
      'type': 'Checkbox',
      'title': 'Checkbox test 2',
      'list': [
        {
          'title': "product 1",
          'value': true,
        },
        {
          'title': "product 2",
          'value': true,
        },
        {
          'title': "product 3",
          'value': false,
        }
      ]
    },
  ]);
  • Example
[ new CoreForm( form: form, onChanged: (dynamic response) { this.response = response; }, ), new RaisedButton( child: new Text('Send'), onPressed: () { print(this.response.toString()); }) ]), ), ), ); }">
 String form_send_email = json.encode([
    {'type': 'Input', 'title': 'Subject', 'placeholder': "Subject"},
    {'type': 'TareaText', 'title': 'Message', 'placeholder': "Content"},
  ]);
 dynamic response;
 
 @override
   Widget build(BuildContext context) {
     return new Scaffold(
       appBar: new AppBar(
         title: new Text(widget.title),
       ),
       body: new SingleChildScrollView(
         child: new Container(
           child: new Column(children: [
             new CoreForm(
               form: form,
               onChanged: (dynamic response) {
                 this.response = response;
               },
             ),
             new RaisedButton(
                 child: new Text('Send'),
                 onPressed: () {
                   print(this.response.toString());
                 })
           ]),
         ),
       ),
     );
   }

When there is a change in the form, the (dynamic response;) is updated,

               onChanged: (dynamic response) {
                 this.response = response;
               },

when text is added to the TextField, add field called response

// initial form_send_email
[{"type":"Input","title":"Subject","placeholder":"Subject"},{"type":"TareaText","title":"Message","placeholder":"Content"}]

// add text (hi) in TextField Message, update dynamic response; and add field called response
[{type: Input, title: Subject, placeholder: Subject}, {type: TareaText, title: Message, placeholder: Content, response: hi }]

Getting Started

For help getting started with Flutter, view our online documentation.

For help on editing package code, view the documentation.

Comments
  • Keyboard Type - Number

    Keyboard Type - Number

    Thanks for this wonderful flutter package. I wonder if there is a way tor restrict the keyboard input type to numbers for entering mobile number details in an input form. Could you guide me on how to set it up?

    opened by kkrishnan90 2
  • The values from RadioButton never updates when i try to click in other option

    The values from RadioButton never updates when i try to click in other option

    It's showing my radio button options but when i try to select a different option of that one was given by default, nothing changes, i know that in flutter we need to re render everything with the setState() but i don't know what i'm missing out, i try to debug the lib and seems like i always receive the same value for the form even if i click in a different option. Thanks

    Center( child: JsonSchema( form: jsonEncode(form), onChanged: (dynamic response) { this.response = response; print(response); fields = JsonForm.fromJson(this.response).fields; form = JsonForm(fields: fields); }, actionSave: (data) { print(data); }, buttonSave: Container( height: 40.0, color: Colors.blueAccent, child: const Center( child: Text("Submit", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold)), ), ), )),

    opened by cesarpatrick 0
  • No named parameter with the name 'autovalidate'. for Flutter 2.8 stable update

    No named parameter with the name 'autovalidate'. for Flutter 2.8 stable update

    flutter/.pub-cache/hosted/pub.dartlang.org/json_to_form-0.0.4/lib/json_schema.dart:338:7: Error: No named parameter with the name 'autovalidate'. autovalidate: formGeneral['autoValidated'] ?? false, ^^^^^^^^^^^^ ../../Downloads/flutter/packages/flutter/lib/src/widgets/form.dart:40:9: Context: Found this candidate, but the arguments don't match. const Form({ ^^^^

    [](url) Screenshot 2021-12-14 at 1 15 11 PM

    opened by theRoushan 3
  • on select item we have black background

    on select item we have black background

    ur plugin awesome but pls resolve this issue when i visit ur code u haven't given [color in drop down button]

        DropdownButton<String>(
                      hint: new Text("Select"),
                      value: formGeneral['fields'][count]['value'],
                      onChanged: (String newValue) {
                        setState(() {
                          formGeneral['fields'][count]['value'] = newValue;
                          _handleChanged();
                        });
                      },
                      items: item['items']
                          .map<DropdownMenuItem<String>>((dynamic data) {
                        return DropdownMenuItem<String>(
                          value: data['value'],
                          child: Container(
                            padding:
                                EdgeInsets.symmetric(horizontal: 5, vertical: 3),
                            decoration: BoxDecoration(color: Colors.white),
                            child: Text(
                              data['label'],
                              style: TextStyle(
                                fontSize: 19,
                                letterSpacing: 0.1,
                                color: Colors.black,
                              ),
                            ),
                          ),
                        );
                      }).toList(),
              
    
    opened by gautamenbake 0
  • select a user (showing by default on

    select a user (showing by default on "select" field) should be labeled text shown on default value select

    hii victor pls help

     {
            'key': 'select1',
            'type': 'Select',
            'label': 'Select test', ---------------------> this should show default on select
            'value': 'product 1',
            'items': [
              {
                'label': "product 1",
                'value': "product 1",
              },
            ]
          },
    
    opened by gautamenbake 0
  • How to get the input field data in valid json format on press of send button

    How to get the input field data in valid json format on press of send button

    Currently the data I am getting in this format which is not a valid json [{ type: Input, title: Hi Group, placeholder: Hi Group flutter, validator: digitsOnly }, { type: Password, title: Password, response: sdfag }, { type: Email, title: Email test, placeholder: hola a todos, response: agsagd }, { type: TareaText, title: TareaText test, placeholder: hola a todos, response: dvgegsdv }, { type: RadioButton, title: Radio Button tests, value: 2, list: [{ title: product 1, value: 1 }, { title: product 2, value: 2 }, { title: product 3, value: 3 }] }, { type: Switch, title: Switch test, switchValue: true }, { type: Checkbox, title: Checkbox test, list: [{ title: product 1, value: true }, { title: product 2, value: false }, { title: product 3, value: false }] }, { type: Checkbox, title: Checkbox test 2, list: [{ title: product 1, value: true }, { title: product 2, value: true }, { title: product 3, value: false }] }]

    I need it in this format:

    `[{ "type": "Input", "title": "Hi Group", "placeholder": "Hi Group flutter", "validator": "digitsOnly" }, { "type": "Checkbox", "title": "Checkbox test", "list": [{ "title": "product 1", "value": true }, { "title": "product 2", "value": false }, { "title": "product 3", "value": true

    	}]
    }
    

    ]`

    opened by sarkaramitabh300 1
  • Issue while getting the data from elastic search and bind it to dropdown.Please help!

    Issue while getting the data from elastic search and bind it to dropdown.Please help!

    I am trying to get the data from elasticsearch and I am trying to bind the same to the dynamic dropdown but I am facing issues. The widgets and data from for loop is not rendering as desired. Can you please help me with this ?

    import 'dart:convert'; import 'package:flutter/material.dart'; import './JsonLib/json_schema.dart'; import './ElasticHttpLib/console_http_transport.dart';

    class AllFields extends StatefulWidget { AllFields({Key key}) : super(key: key); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect // how it looks.

    // This class is the configuration for the state. It holds the values (in this // case the title) provided by the parent (in this case the App widget) and // used by the build method of the State. Fields in a Widget subclass are // always marked "final".

    @override _AllFields createState() => new _AllFields(); }

    class _AllFields extends State { List data; static List runtime; String form;

    Future getResponse() async { final client = Client(ConsoleHttpTransport( Uri.parse(url)));

    // bucket aggregation
    final rs3 = await client.search(
        '_module', '_doc', null,
        aggregations: {
          'dropdown': {
            'terms': {'field': 'reasonForReporting', 'size': 10}
          }
        }).then((response) {
      setState(() {
        var res = response.aggregations['dropdown'].buckets.toList();
    
        data = res;
        runtime = data;
      });
    }).catchError((e) {
      print(e);
    });
    

    }

    @override void initState() { getResponse(); super.initState(); }

    @override void didChangeDependencies() { getResponse();

    super.didChangeDependencies();
    

    }

    dynamic response;

    @override Widget build(BuildContext context) { // This method is rerun every time setState is called, for instance as done // by the _incrementCounter method above. // // The Flutter framework has been optimized to make rerunning build methods // fast, so that you can just rebuild anything that needs updating rather // than having to individually change instances of widgets. if (runtime != null) { form = json.encode({ 'title': 'Test Form Json Schema', 'description': 'My Description', 'autoValidated': true, 'fields': [ { 'key': 'input1', 'type': 'Input', 'label': 'Hi Group', 'placeholder': "Hi Group flutter", 'value': '', 'required': true }, { 'key': 'password1', 'type': 'Password', 'label': 'Password', 'required': true }, { 'key': 'email1', 'type': 'Email', 'label': 'Email test', 'placeholder': "hola a todos" }, { 'key': 'tareatext1', 'type': 'TareaText', 'label': 'TareaText test', 'placeholder': "hola a todos" }, { 'key': 'radiobutton1', 'type': 'RadioButton', 'label': 'Radio Button tests', 'value': 2, 'items': [ { 'label': "product 1", 'value': 1, }, { 'label': "product 2", 'value': 2, }, { 'label': "product 3", 'value': 3, } ] }, { 'key': 'switch1', 'type': 'Switch', 'label': 'Switch test', 'value': false, }, { 'key': 'checkbox1', 'type': 'Checkbox', 'label': 'Checkbox test', 'items': [ { 'label': "product 1", 'value': true, }, { 'label': "product 2", 'value': false, }, { 'label': "product 3", 'value': false, } ] }, { 'key': 'select1', 'type': 'Select', 'label': 'Select value', 'value': 'product 1', 'items': [ { 'label': "product 1", 'value': "product 1", }, { 'label': "product 2", 'value': "product 2", }, { 'label': "product 3", 'value': "product 3", }, { for (int i = 0; i < runtime.length; i++) { 'label': runtime[i].key.toString(), 'value': runtime[i].key.toString(), } } ] }, ] });

      return new Scaffold(
        appBar: new AppBar(
          // Here we take the value from the MyHomePage object that was created by
          // the App.build method, and use it to set our appbar title.
          title: new Text("All Fields"),
        ),
        body: new SingleChildScrollView(
          child: new Container(
            // Center is a layout widget. It takes a single child and positions it
            // in the middle of the parent.
            child: new Column(children: <Widget>[
              new JsonSchema(
                form: form,
                onChanged: (dynamic response) {
                  this.response = response;
                  print(response);
                },
                actionSave: (data) {
                  print(data);
                },
                buttonSave: new Container(
                  height: 40.0,
                  color: Colors.blueAccent,
                  child: Center(
                    child: Text("Send",
                        style: TextStyle(
                            color: Colors.white, fontWeight: FontWeight.bold)),
                  ),
                ),
              ),
            ]),
          ),
        ),
      );
    } else {
      return new Scaffold(
          appBar: new AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: new Text("All Fields"),
      ));
    }
    

    } }

    opened by chandk87 0
Owner
Victor Alfonso Rodas Oña
Victor Alfonso Rodas Oña
Flutter form fields designed to take much of the burden of form-related coding off the programmer's back — masks, validations, keyboard type, etc.

well_formed Contents Overview Getting Started Demo application References Overview Well-Formed Widget Fields - Well-Formed - is a collection of Flutte

Dartoos 7 Nov 2, 2022
A Flutter package that provides a dropdown form field using a dropdown button inside a form field.

Dropdown form field A dropdown form field using a dropdown button inside a form field. Demo Features Can be used as regular form field. Simple to impl

Carlos Eugenio Torres 72 Jan 1, 2023
Form builder image picker - Form builder image picker for flutter

form_builder_image_picker Field for picking image(s) from Gallery or Camera for

Ferri Sutanto 0 Jan 28, 2022
Jannis 0 Jan 29, 2022
User auth form - Signup and signin user auth form with ability to stay signed in and have an option to signout.

user_auth_form SIgnup and signin user authentification form Getting Started This project is a starting point for a Flutter application. A few resource

null 0 Jan 6, 2022
Flutter package: Json Table Widget to create table from json array

Json Table Widget ?? Proudly Sponsored by FieldAssist Request a Demo This Flutter package provides a Json Table Widget for directly showing table from

Ayush P Gupta 193 Jan 7, 2023
Fluter-json - App Demonstrating JSON Data Parsing with various flutter widgets

users_list Flutter App to Demonstrate JSON Parsing Getting Started This project is a starting point for a Flutter application. A few resources to get

Khurram Rizvi 5 Jul 10, 2021
Json editor - A json editor on flutter

Features Support add comment; Support show errors for invalid json text; Pretty

Chan Young 12 Nov 18, 2022
State Persistence - Persist state across app launches. By default this library store state as a local JSON file called `data.json` in the applications data directory. Maintainer: @slightfoot

State Persistence Persist state across app launches. By default this library store state as a local JSON file called data.json in the applications dat

Flutter Community 70 Sep 28, 2022
Given a JSON string, this library will generate all the necessary Dart classes to parse and generate JSON.

JSON to Dart Given a JSON string, this library will generate all the necessary Dart classes to parse and generate JSON. This library is designed to ge

Javier Lecuona 1.2k Dec 25, 2022
A cross-platform flutter package to convert your links into rich beautiful previews.

Link Preview Generator A cross-platform flutter package to convert your links into rich beautiful previews. This package is inspired from Any Link Pre

Pranav Bedre 12 Oct 21, 2022
Convert Widget To Image in Flutter

Convert Widget To Image You can transform all of your widgets into images in Flu

Behruz Hurramov 1 Dec 28, 2022
Color-Converter - A minimalist application made with flutter to convert hexadecimal colors to RGB colors and vise-versa.

Color Converter A minimalist application made with flutter to convert hexadecimal colors to RGB colors and vise-versa for Flutter Create Competition.

Poojan Pandya 2 Sep 16, 2020
C2F can convert css style to Flutter code online.

C2F is an interesting little project. I hope to find a way to convert css styles to flutter styles. I believe many web developers will like it. https:

Anonymous Namespace 232 Dec 29, 2022
A simple dart package to convert large numbers to a human readable format. 1278 to 1.2K instead, for example.

A simple dart package to convert large numbers to a human readable format. 1278 to 1.2K instead, for example. Features Represents large numbers in ter

Rohit V 1 Oct 8, 2022
Csv to list for web - Convert a CSV into a list in order to populate a firebase database

My goal is to convert a CSV into a list in order to populate a firebase database

null 0 Jan 26, 2022
A free tool to convert any website into a cross platform native application.

SWAB (Spyxpo Web to App Builder) Convert any website into an iOS/Android/Windows/macOS/Linux app. This is a preview build for testing purposes major u

Spyxpo 7 Jan 1, 2023
This library helps you to convert Delta to HTML. Based on Flutter_Quill Delta

Delta_To_HTML This library helps you to convert Delta to HTML. Based on Flutter_Quill Delta [ currently in under development ] Usage import 'package:d

Secanonm 4 Dec 20, 2022
🚗 Apple CarPlay for Flutter Apps. Aims to make it safe to use apps made with Flutter in the car by integrating with CarPlay.

CarPlay with Flutter ?? Flutter Apps now on Apple CarPlay! flutter_carplay aims to make it safe to use iPhone apps made with Flutter in the car by int

OÄŸuzhan Atalay 156 Dec 26, 2022