Flutter问卷调查插件survey_form的使用

Flutter问卷调查插件survey_form的使用

survey_form包

survey_form 包是一个全面的解决方案,用于创建问卷调查表单。

特性

  • 问卷调查页面:该包包含几个页面,如 survey_form.dartsurvey_form_boundary_view.dartsurvey_form_view.dart,这些页面提供了创建问卷调查表单的用户界面。

  • 问卷调查BLoCs:它提供了多种BLoCs用于状态管理,使用了BLoC模式。这些BLoCs处理了问卷调查表单的业务逻辑。

  • 问卷调查模型:定义了各种数据模型,如 ServiceModelServiceDefinitionModel 等,用于问卷调查表单的创建过程。

  • 问卷调查仓库:该包提供了抽象类作为数据仓库,如 ServiceDefinitionLocalRepositoryServiceLocalRepositoryServiceDefinitionRemoteRepositoryServiceRemoteRepository,可以扩展以创建不同服务模型的数据仓库。它还包括错误处理,如 InvalidApiResponseException

入门指南

要使用此包,请将以下依赖项添加到您的 pubspec.yaml 文件中:

dependencies:
  survey_form: ^any

使用方法

要导航到任何屏幕,请首先将 survey_form_router 添加到您的主应用路由中:

context.router.push(SurveyFormWrapperRoute());

SurveyForm 包需要从主应用传递以下数据:

String _projectId = '';
String _projectName = '';
String _loggedInIndividualId = '';
String _loggedInUserUuid = '';
String _appVersion = '';
String _tenantId = '';
Object _roles;
bool _isHealthFacilityWorker;
BoundaryModel? _boundaryModel;
PersistenceConfiguration _persistenceConfiguration;

完整示例

以下是一个完整的示例代码,展示了如何使用 survey_form 包。

import 'dart:convert';

import 'package:digit_ui_components/digit_components.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:survey_form/blocs/app_localization.dart';
import 'package:survey_form/blocs/survey_form_localization_delegate.dart';
import 'package:survey_form/pages/acknowledgement.dart';

import 'localizedString.dart';

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

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

  // This widget is the root of your application.
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Survey Form Package Example'),
    );
  }
}

Future<List> loadLocalizedStrings() async {
  String jsonString = await rootBundle.loadString('lib/data.json');
  // 解码JSON字符串
  List<dynamic> jsonList = jsonDecode(jsonString);

  // 将动态列表转换为LocalizedString对象列表
  return jsonList
      .map((jsonItem) => LocalizedString.fromJson(jsonItem))
      .toList();
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late Future<dynamic> localizedStrings;
  final languages = [
    {"label": "PORTUGUÊS", "value": "pt_MZ"},
    {"label": "FRENCH", "value": "fr_MZ"},
    {"label": "ENGLISH", "value": "en_MZ"}
  ];

  [@override](/user/override)
  void initState() {
    super.initState();
    localizedStrings = loadLocalizedStrings();

    SurveyFormLocalizationDelegate delegate =
        SurveyFormLocalizationDelegate(localizedStrings, languages);
    delegate.load(const Locale("en", "MZ"));
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: SizedBox(
          width: 300,
          child: DigitButton(
            label: "Acknowledgement Page",
            size: DigitButtonSize.large,
            onPressed: () {
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (BuildContext context) =>
                      SurveyFormAcknowledgementPage(
                        appLocalizations: SurveyFormLocalization(
                            const Locale("en", "MZ"),
                            localizedStrings,
                            languages),
                      )));
            },
            type: DigitButtonType.primary,
          ),
        ),
      ),
    );
  }
}

更多关于Flutter问卷调查插件survey_form的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter问卷调查插件survey_form的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中,如果你想创建一个问卷调查或表单,可以使用 survey_form 插件。这个插件可以帮助你轻松地创建和管理复杂的问卷调查。以下是如何使用 survey_form 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  survey_form: ^0.0.1 # 请检查最新版本

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

2. 导入包

在你的 Dart 文件中导入 survey_form 包:

import 'package:survey_form/survey_form.dart';

3. 创建问卷调查

你可以使用 SurveyForm 小部件来创建问卷调查。以下是一个简单的示例:

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

class MySurveyPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('问卷调查'),
      ),
      body: SurveyForm(
        questions: [
          Question(
            question: '您对本次服务的满意度如何?',
            type: QuestionType.singleChoice,
            options: ['非常满意', '满意', '一般', '不满意', '非常不满意'],
          ),
          Question(
            question: '您对我们的产品有哪些建议?',
            type: QuestionType.text,
          ),
          Question(
            question: '您经常使用我们的哪些产品?',
            type: QuestionType.multipleChoice,
            options: ['产品A', '产品B', '产品C', '产品D'],
          ),
        ],
        onSubmit: (Map<String, dynamic> responses) {
          // 在这里处理提交的问卷数据
          print(responses);
        },
      ),
    );
  }
}

4. 解释代码

  • SurveyForm 是主要的小部件,用于显示问卷调查。
  • questions 参数是一个 List<Question>,每个 Question 代表一个问题。
  • Questiontype 属性定义了问题的类型,可以是 QuestionType.singleChoice(单选)、QuestionType.multipleChoice(多选)或 QuestionType.text(文本输入)。
  • options 属性用于定义选择题的选项。
  • onSubmit 是一个回调函数,当用户提交问卷时触发,返回用户的所有回答。

5. 运行应用

现在你可以运行你的 Flutter 应用,并查看问卷调查的效果。用户可以选择或输入答案,并提交问卷。

6. 处理提交的数据

onSubmit 回调中,你可以处理用户提交的数据。例如,你可以将数据发送到服务器或存储在本地数据库中。

onSubmit: (Map<String, dynamic> responses) {
  // 将数据发送到服务器或存储在本地
  print('用户提交的问卷数据: $responses');
},

7. 自定义样式

你可以根据需要自定义问卷调查的样式。SurveyForm 小部件可能提供了一些样式选项,或者你可以通过包装它来自定义样式。

8. 处理验证

你可以在 SurveyForm 中添加验证逻辑,以确保用户填写了所有必填问题。

SurveyForm(
  questions: [
    Question(
      question: '您对本次服务的满意度如何?',
      type: QuestionType.singleChoice,
      options: ['非常满意', '满意', '一般', '不满意', '非常不满意'],
      isRequired: true, // 设置为必填问题
    ),
    // 其他问题
  ],
  onSubmit: (Map<String, dynamic> responses) {
    if (responses.containsKey('您对本次服务的满意度如何?') && responses['您对本次服务的满意度如何?'].isEmpty) {
      // 处理未填写必填问题的情况
      print('请填写所有必填问题!');
    } else {
      // 处理提交的数据
      print(responses);
    }
  },
),
回到顶部