Flutter JSON数据转Widget插件json_to_widget的使用

Flutter JSON数据转Widget插件json_to_widget的使用

Installation(安装)

在你的 pubspec.yaml 文件中添加以下依赖:

dependencies:
    json_to_widget

然后通过命令行安装包:

$ flutter packages get

JsonWidget(JSON数据转Widget)

JsonWidget 是插件的核心组件,用于将 JSON 数据转换为 Flutter 的 Widget。

示例代码:

JsonWidget(
    decorations: decorations,
    form: form,
    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)),
        ),
    ),
),

Attribute(属性)

以下是 JsonWidget 的主要属性说明:

  • form (Type String):你的表单以字符串形式表示。
  • onChanged (Type Function):每次表单发生变化时调用该函数。
  • padding (Type Double):设置内边距。
  • formMap (Type Map):你的表单以 Map 形式表示。
  • errorMessages (Type Map):自定义错误信息。
  • validations (Type Map):添加验证规则。
  • decorations (Type Map):添加装饰样式。
  • buttonSave (Type Widget):自定义保存按钮(注意不是 RaisedButton,因为 onClick 存在问题)。
  • actionSave (Type Function):当点击 buttonSave 时调用的函数。

Form(表单)

可以创建 JSON 字符串形式的表单或直接传入 Map。

创建 Form String
String formString = json.encode({
    'title': 'form example',
    'description': '',
    'autoValidated': true, // 默认值为 false
    'fields': [
        // 字段列表
    ]
});
创建 Form Map
Map formMap = {
    'title': 'form example',
    'description': '',
    'autoValidated': true, // 默认值为 false
    'fields': [
        // 字段列表
    ]
};

Fields(字段)

所有字段都有一个默认隐藏标签的属性(labelHidden,默认值为 false)。每个字段必须有唯一的键值(key),以便进行验证。

TextInput 或 Input(文本输入)

以下是 TextInputInput 的示例:

JSON 字符串示例
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
        },
    ]
});
JSON Map 示例
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
        },
    ]
};

如何为表单字符串添加验证?

JsonWidget 中有 validationsdecorations 属性。每个字段必须具有唯一的键值。

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

Map validations = {
    'inputKey': validationExample,
};

dynamic response;

JsonWidget(
    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(下拉选择框)

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",
                   }
                 ]
         }
    ],
 });

当 TextField 中添加文本时,更新动态响应字段

// 初始表单
[{"type":"Input","title":"Subject","placeholder":"Subject"},{"type":"TextArea","title":"Message","placeholder":"Content"}]

// 在 Message TextField 中添加文本 "hi",更新动态响应字段
[{type: Input, title: Subject, placeholder: Subject}, {type: TextArea, title: Message, placeholder: Content, response: hi}]

Json to Widget(JSON 转 Widget)

在 Dart 代码中导入插件:

import 'package:json_to_widget/json_to_widget.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(示例)

完整的示例代码如下:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:json_to_widget/json_to_widget.dart';

void main() {
  runApp(HomePage());
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String form = json.encode({
    'fields': [
      {
        'key': 'input1',
        'type': 'Input',
        'label': 'Username',
        'placeholder': "Enter Your Username",
        'required': true
      },
      {
        'key': 'password1',
        'type': 'Password',
        'label': 'Password',
        'required': true
      },
    ]
  });

  dynamic response;

  Map decorations = {
    'input1': InputDecoration(
        prefixIcon: Icon(Icons.account_box), border: OutlineInputBorder()),
    'password1': InputDecoration(
        prefixIcon: Icon(Icons.security), border: OutlineInputBorder())
  };

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Login"),
      ),
      body: Column(
        children: <Widget>[
          const Text(
            "Login Form",
            style: TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold),
          ),
          JsonWidget(
            decorations: decorations,
            form: form,
            onChanged: (dynamic response) {
              this.response = response;
            },
            actionSave: (data) {
              print(data);
            },
            buttonSave: Container(
              height: 40.0,
              color: Colors.blueAccent,
              child: const Center(
                child: Text("Login",
                    style: TextStyle(
                        color: Colors.white, fontWeight: FontWeight.bold)),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

当表单发生变化时,动态响应字段被更新

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

当 TextField 中添加文本时,更新动态响应字段

// 初始表单
[{"type":"Input","title":"Subject","placeholder":"Subject"},{"type":"TareaText","title":"Message","placeholder":"Content"}]

// 在 TextField Message 中添加文本 "hi",更新动态响应字段
[{type: Input, title: Subject, placeholder: Subject}, {type: TareaText, title: Message, placeholder: Content, response: hi}]

更多关于Flutter JSON数据转Widget插件json_to_widget的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter JSON数据转Widget插件json_to_widget的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中,json_to_widget 是一个用于将JSON数据转换为Widget的插件。它可以帮助开发者动态生成UI组件,特别适用于需要根据后端返回的JSON数据动态构建界面的场景。

安装插件

首先,你需要在 pubspec.yaml 文件中添加 json_to_widget 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  json_to_widget: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

使用示例

以下是一个简单的示例,展示如何使用 json_to_widget 将JSON数据转换为Widget。

1. 导入包

import 'package:flutter/material.dart';
import 'package:json_to_widget/json_to_widget.dart';

2. 定义JSON数据

final jsonData = '''
{
  "type": "Column",
  "children": [
    {
      "type": "Text",
      "data": "Hello, World!",
      "style": {
        "fontSize": 24,
        "color": "#FF0000"
      }
    },
    {
      "type": "RaisedButton",
      "child": {
        "type": "Text",
        "data": "Click Me"
      },
      "onPressed": "onButtonPressed"
    }
  ]
}
''';

3. 创建Widget

class MyHomePage extends StatelessWidget {
  void onButtonPressed() {
    print("Button Pressed!");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('JSON to Widget Example'),
      ),
      body: JsonToWidget.fromJson(
        jsonData,
        context,
        callbacks: {
          'onButtonPressed': onButtonPressed,
        },
      ),
    );
  }
}

4. 运行应用

void main() => runApp(MaterialApp(
  home: MyHomePage(),
));
回到顶部