flow_form 0.1.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 59

Flow Form #

This is Flow Form library help to design a flow of form using a JSON file in given Format.

How it looks #

How it works #

The file will have a flow which will be converted internally into a tree structure with given branching in the file and will maintain and update the states of the form using the redux internally. Currently, it's an acyclic tree.

Getting Started #

First, we need to create a JSON file representing our form flow using the given format and then provide that path to the library.

It consists of three component FlowForm to get started.

  1. Builder
  2. Provider
  3. Notifier

1. Build the Form #

We need to build our form by setting the required JSON flow file path and other optional properties.

final flowFormBuilder = FlowFormBuilder('assets/json/flow.json')
    ..screenMetaPath = 'assets/json/screen_data.json'
    ..database = DatabaseImpl()
    ..registerWidget = (String type) {
      switch (type) {
        case SelectScreen.type:
          return SelectScreen();
        case DatePickerScreen.type:
          return DatePickerScreen();
        case TextInputScreen.type:
          return TextInputScreen();
        case FileUploadScreen.type:
          return FileUploadScreen();
        default:
          return const Center(
            child: Text('Form Ends Here'),
          );
      }
    };
final FlowForm = flowFormBuilder.build();

2. FlowFormProvider #

We need to pass the FlowForm which we got from above builder to FlowFormProvider widget.

FlowFormProvider(
  flowForm: flowForm,
  child: MaterialApp(
    // Top Parent Widget
  ),
)

This best practice is to wrap this FlowFormProvider to the topmost parent widget.

3. FlowFormNotifier #

To get the update to to display a form, we need to wrap the widget into FlowFormNotifier which requires a widget in return we want to build on the basic of current formMetadata .

@override
Widget build(BuildContext context) {
  var formProvider = FlowFormProvider.of(context);
  return FlowFormNotifier(builder: (formMetadata) {
    if (formMetadata != null) {
      return formProvider.getWidget(formMetadata.screenType);
    }
    return Container();
  });
}

We can use formProvider.getWidget(type) to get widget we registered in the FlowFormBuilder.

Setup Custom Database #

We can also add our database implementation by implementing the Database class and setting up in the app like this.

my_database_impl.dart

class MyDatabaseImpl implements Database {
  ///Function to save data
  void saveData({StoreViewModel viewModel, dynamic answer}) {
    // my save implementation
  }

  ///Example Function to upload image to fireBase
  void uploadImage() {
  }

  String getData(String dataKey) {
   // key to fetch screen data and save user input in db.
    var box = Hive.box('DataBox');
    String data = box.get(dataKey);
    DataStorage.updateData(dataKey, data);
    return data;
  }
}

JSON Format #

This is how ths json should be formatted.

{
  "questionIds": [
    "question_id_1",
    "question_id_2",
    "question_id_3"
  ],
  "nextQuestion": {
    "answerBranch": {
      "yes": {
        "questionIds": [
          "question_id_4",
          "question_id_5"
        ],
        "nextQuestion": {
          "answerBranch": {
            "private": {
              "questionIds": [
                "end"
              ],
              "nextQuestion": {
                "answerBranch": {}
              }
            },
            "public": {
              "questionIds": [
                "end"
              ],
              "nextQuestion": {
                "answerBranch": {}
              }
            }
          }
        }
      },
      "no": {
        "questionIds": [
          "question_id_6",
          "ends"
        ],
        "nextQuestion": {
          "answerBranch": {}
        }
      }
    }
  }
}

Note :

  1. Where questionIds are the list of ids which we used to fetch screen data of the specific question.
  2. The answerBranch the branching part where we navigate to different flow based on the selected answer.
  3. Keep the all json keys in camel case to keep the consistency.

Made with ❤️ from Technogise

BSD 3-Clause License #

Copyright (c) 2020, Technogise Private Limited All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

  3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

[0.1.0] - 15 April 2020. #

  • This is alpha version of the library. The API are subjected to changed

example/lib/main.dart

import 'package:back_button_interceptor/back_button_interceptor.dart';
import 'package:flow_form/flow_form.dart';
import 'package:flow_form/form.dart';
import 'package:flow_form/question_navigation.dart';
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart' as path_provider;
import 'database_impl.dart';
import 'styles/theme.dart';
import 'widgets/screens/date_picker_screen.dart';
import 'widgets/screens/file_upload_screen.dart';
import 'widgets/screens/main_screen.dart';
import 'widgets/screens/select_screen.dart';
import 'widgets/screens/text_input_screen.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  initHiveDB();

  final flowFormBuilder = FlowFormBuilder('assets/json/flow.json')
    ..screenMetaPath = 'assets/json/screen_data.json'
    ..database = DatabaseImpl()
    ..registerWidget = (String type) {
      switch (type) {
        case SelectScreen.type:
          return SelectScreen();
        case DatePickerScreen.type:
          return DatePickerScreen();
        case TextInputScreen.type:
          return TextInputScreen();
        case FileUploadScreen.type:
          return FileUploadScreen();
        default:
          return const Center(
            child: Text('Form Ends Here'),
          );
      }
    };

  runApp(MyApp(flowFormBuilder.build()));
}

///MyApp entry of form builder sample
class MyApp extends StatelessWidget {
  MyApp(this.flowForm);

  /// Static variable to refer this class in routes
  static const id = '/';

  final FlowForm flowForm;

  @override
  Widget build(BuildContext context) {
    QuestionNavigation questionNavigation =
        FlowFormProvider.navigatorOf(context);
    BackButtonInterceptor.add((value) {
      if (questionNavigation.isRoot()) {
        return false;
      }
      questionNavigation.gotoPrevious();
      return true;
    });
    return FlowFormProvider(
      flowForm: flowForm,
      child: MaterialApp(
        theme: appTheme,
        home: Scaffold(
          appBar: AppBar(
            leading: BackButton(onPressed: () {
              questionNavigation.gotoPrevious();
            }),
          ),
          body: SafeArea(child: Center(child: MainScreen())),
        ),
        debugShowCheckedModeBanner: false,
      ),
    );
  }
}

void initHiveDB() async {
  final appDocumentDirectory =
      await path_provider.getApplicationDocumentsDirectory();
  Hive.init(appDocumentDirectory.path);
  await Hive.openBox("DataBox");
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flow_form: ^0.1.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flow_form/flow_form.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
19
Health:
Code health derived from static analysis. [more]
98
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
59
Learn more about scoring.

We analyzed this package on Jul 11, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.14
  • Flutter: 1.17.5

Analysis suggestions

Package not compatible with SDK dart

Because:

  • flow_form that is a package requiring null.

Health suggestions

Fix lib/helpers/data_storage.dart. (-1.49 points)

Analysis of lib/helpers/data_storage.dart reported 3 hints:

line 4 col 8: Unused import: '../redux/actions/actions.dart'.

line 5 col 8: Unused import: '../redux/store.dart'.

line 23 col 12: The value of the local variable 'key' isn't used.

Fix lib/helpers/common.dart. (-1 points)

Analysis of lib/helpers/common.dart reported 2 hints:

line 20 col 7: Dead code.

line 20 col 7: Avoid empty statements.

Format lib/redux/app_state.dart.

Run flutter format to format lib/redux/app_state.dart.

Format lib/redux/reducers.dart.

Run flutter format to format lib/redux/reducers.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
collection ^1.14.11 1.14.12 1.14.13
flutter 0.0.0
flutter_redux ^0.6.0 0.6.0
http ^0.12.0+4 0.12.1
redux >=4.0.0 <5.0.0 4.0.0
Transitive dependencies
charcode 1.1.3
http_parser 3.1.4
meta 1.1.8 1.2.2
path 1.7.0
pedantic 1.9.0 1.9.2
sky_engine 0.0.99
source_span 1.7.0
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6 1.2.0
vector_math 2.0.8 2.1.0-nullsafety
Dev dependencies
effective_dart ^1.2.0
flutter_test