Flutter内容创建或管理插件content_foundry的使用

发布于 1周前 作者 wuwangju 来自 Flutter

Flutter内容创建或管理插件content_foundry的使用

Form-like UI用于编辑各种用户定义的内容。可以用于CMS前端。

该包目前处于活跃开发阶段——API可能会更改。

功能

  • 支持的类型:

    • bool
    • String
    • double
    • enum - 从String列表中选择
    • structure - 带命名字段的集合
    • list - 字段列表
    • polymorphic - 可以有多种不同类型的字段(类似于JSON Schema的anyOf
    • nullable - 包裹任何字段的“包装器”字段,使其可为空(其他字段默认不可为空)
  • 自定义字段。

  • 自定义字段编辑器。

  • 覆盖默认字段编辑器。

使用方法

示例代码

以下是一个完整的示例代码,展示了如何使用content_foundry插件来创建和管理内容。

import 'dart:convert';

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Content Foundry Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const ContentFoundryPage(),
    );
  }
}

class ContentFoundryPage extends StatefulWidget {
  const ContentFoundryPage({super.key});

  [@override](/user/override)
  State<ContentFoundryPage> createState() => _ContentFoundryPageState();
}

class _ContentFoundryPageState extends State<ContentFoundryPage> {
  late Field _field;
  late String _formattedValue;

  final _encoder = JsonEncoder.withIndent(' ' * 2);

  [@override](/user/override)
  void initState() {
    super.initState();
    // 初始化字段
    _field = StructureField(
      properties: [
        StructureFieldProperty(
          name: 'Outer list',
          field: ListField(
            fieldFactory: (initialValue) {
              return PolymorphicField(
                typeFieldName: 'type',
                valueFieldName: 'value',
                initialValue: initialValue is Map<String, dynamic> ? initialValue : const {},
                types: [
                  PolymorphicFieldType(
                    type: 'text',
                    displayName: 'Text',
                    description: '多行文本,可选对齐方式。',
                    fieldFactory: (defaultData) => StructureField.fromFieldMap(
                      fieldByName: {
                        'text': StringField(maxLines: null),
                        'align': EnumField(
                          choices: ['left', 'center', 'right', 'justify'],
                        ).nullable(isNull: true),
                      },
                    ),
                  ),
                  PolymorphicFieldType(
                    type: 'image',
                    displayName: 'Image',
                    description: '互联网上的图片,可选宽高比。',
                    fieldFactory: (defaultData) => StructureField.fromFieldMap(
                      fieldByName: {
                        'url': StringField(),
                        'aspect_ratio': DoubleField().nullable(),
                      },
                    ),
                  ),
                  PolymorphicFieldType(
                    type: 'button',
                    displayName: 'Button',
                    description: '可配置强调的按钮。',
                    fieldFactory: (defaultData) => StructureField.fromFieldMap(
                      fieldByName: {
                        'title': StringField(),
                        'link': StringField().nullable(),
                        'emphasis': EnumField(
                          choices: ['primary', 'secondary', 'warning'],
                          value: 'primary',
                        ),
                      },
                    ),
                  ),
                ],
              );
            },
          ),
        ),
        StructureFieldProperty(
          name: 'Another outer list',
          field: ListField(
            fieldFactory: (initialValue) {
              return ListField(
                fieldFactory: (initialValue) => StringField(),
              );
            },
          ),
        ),
        StructureFieldProperty(
          displayName: '浮点数',
          name: 'double',
          field: DoubleField(),
        ),
        StructureFieldProperty(
          name: 'string',
          description: '多行文本',
          field: StringField(
            value: '初始字符串值',
            maxLines: null,
          ),
        ),
        StructureFieldProperty(
          displayName: '可空枚举',
          name: 'enum',
          field: EnumField(
            choices: ['left', 'center', 'right', 'justify'],
          ).nullable(isNull: true),
        ),
        StructureFieldProperty(
          displayName: '多态',
          description: '此字段可以包含不同类型的数据',
          name: 'polymorphic',
          field: PolymorphicField(
            typeFieldName: 'type',
            valueFieldName: 'value',
            types: [
              PolymorphicFieldType(
                type: 'text',
                displayName: 'Text',
                description: '多行文本,可选对齐方式。',
                fieldFactory: (defaultData) => StructureField.fromFieldMap(
                  fieldByName: {
                    'text': StringField(maxLines: null),
                    'align': EnumField(
                      choices: ['left', 'center', 'right', 'justify'],
                    ).nullable(isNull: true),
                  },
                ),
              ),
              PolymorphicFieldType(
                type: 'image',
                displayName: 'Image',
                description: '互联网上的图片,可选宽高比。',
                fieldFactory: (defaultData) => StructureField.fromFieldMap(
                  fieldByName: {
                    'url': StringField(),
                    'aspect_ratio': DoubleField().nullable(),
                  },
                ),
              ),
              PolymorphicFieldType(
                type: 'button',
                displayName: 'Button',
                description: '可配置强调的按钮。',
                fieldFactory: (defaultData) => StructureField.fromFieldMap(
                  fieldByName: {
                    'title': StringField(),
                    'link': StringField().nullable(),
                    'emphasis': EnumField(
                      choices: ['primary', 'secondary', 'warning'],
                      value: 'primary',
                    ),
                  },
                ),
              ),
            ],
          ),
        ),
      ],
    );
    _updateValue();
    _field.addListener(_onChange);
  }

  [@override](/user/override)
  void dispose() {
    _field.dispose();
    super.dispose();
  }

  void _onChange() {
    _updateValue();
    setState(() {});
  }

  void _updateValue() => 
      _formattedValue = _field.isValid() ? _encoder.convert(_field.getValue()) : 'Invalid';

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Content Foundry'),
      ),
      body: Center(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Flexible(
              child: SingleChildScrollView(
                child: ContentFoundryEditor(
                  field: _field,
                ),
              ),
            ),
            Flexible(
              child: Text(_formattedValue),
            ),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter内容创建或管理插件content_foundry的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter内容创建或管理插件content_foundry的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


content_foundry 是一个用于 Flutter 的内容创建和管理插件。它可以帮助开发者在应用中轻松地创建、管理和展示动态内容。以下是如何使用 content_foundry 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  content_foundry: ^latest_version

然后运行 flutter pub get 来获取依赖。

2. 初始化插件

在你的 Flutter 应用中初始化 content_foundry 插件。通常,你可以在 main.dart 文件中进行初始化:

import 'package:content_foundry/content_foundry.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 ContentFoundry
  await ContentFoundry.initialize(
    apiKey: 'YOUR_API_KEY',
    projectId: 'YOUR_PROJECT_ID',
  );

  runApp(MyApp());
}

3. 获取内容

使用 ContentFoundry 来获取和管理内容。你可以通过以下方式获取内容:

import 'package:content_foundry/content_foundry.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Content Foundry Example'),
        ),
        body: FutureBuilder(
          future: ContentFoundry.getContent('content_id'),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            } else if (snapshot.hasError) {
              return Center(child: Text('Error: ${snapshot.error}'));
            } else {
              var content = snapshot.data;
              return Center(
                child: Text(content['title']),
              );
            }
          },
        ),
      ),
    );
  }
}

4. 管理内容

content_foundry 还提供了管理内容的功能,例如创建、更新和删除内容。你可以使用以下方法来管理内容:

// 创建内容
await ContentFoundry.createContent({
  'title': 'New Content',
  'body': 'This is a new content created using ContentFoundry.',
});

// 更新内容
await ContentFoundry.updateContent('content_id', {
  'title': 'Updated Content',
  'body': 'This content has been updated.',
});

// 删除内容
await ContentFoundry.deleteContent('content_id');

5. 监听内容变化

你还可以监听内容的变化,以便在内容更新时自动刷新 UI:

ContentFoundry.onContentChanged('content_id').listen((content) {
  print('Content changed: $content');
});

6. 处理错误

在使用 content_foundry 时,可能会遇到各种错误。你可以通过捕获异常来处理这些错误:

try {
  var content = await ContentFoundry.getContent('content_id');
} catch (e) {
  print('Error: $e');
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!