peiffer-innovations / json_dynamic_widget

MIT License
223 stars 67 forks source link

how to achieve registerFunctions also dynamic json file, now i declare registerFunctions as Map . #299

Open vijaymsc opened 4 months ago

vijaymsc commented 4 months ago
main.dart

import 'dart:convert';
import 'package:json_dynamic_widget/json_dynamic_widget.dart';
import 'package:http/http.dart' as http;

void main() {
  launcher();
}

void launcher() {

  WidgetsFlutterBinding.ensureInitialized();

  final registry = JsonWidgetRegistry.instance;

  Map<String, JsonWidgetFunction> registryFunc = {

    "validateForm": ({args, required registry}) => () async {
          final BuildContext context = registry.getValue(args![0]);
          bool valid = Form.of(context).validate();
          if (valid) {
            var userName = registry.getValue('user_email');
            var userPassword = registry.getValue('user_password');
          bool status = await validateUserData(userName, userPassword);
          if(status)
            {
              registry.setValue('user_email', '');
              registry.setValue('user_password', '');
            }
            showSnackBar(context,status?"Login Success": "Login Failed");

          }
        }

  };
  registry.registerFunctions(registryFunc);

  runApp(const MaterialApp(
    debugShowCheckedModeBanner: false,
    home: AuthLogin(),
  ));
}

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

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<String>(
        future: getJsonWidget(),
        builder: (context, snapShot) {
          if (snapShot.connectionState == ConnectionState.done) {
            final registry = JsonWidgetRegistry.instance.copyWith();
            final widget = JsonWidgetData.fromDynamic(
              json.decode(snapShot.data!),
              registry: registry,
            );
            return widget.build(context: context);
          }
          return const Center(child: CircularProgressIndicator());
        });
  }

  Future<String> getJsonWidget() async {
    String jsonData =
        await rootBundle.loadString('assets/example/user_auth.json');
    return jsonData;
  }
}
Future<bool> validateUserData(
    String userEmail, String password) async {
  var map = {"email": userEmail, "password": password};
  print(map);
  var result =
      await http.post(Uri.parse('https://reqres.in/api/login'), body: map);
  print('${result.statusCode}');
  if (result.statusCode == 200 || result.statusCode == 201) {

    return true;
  }
  return false;
}

showSnackBar(BuildContext context,String content){
  ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(content)));
}

user_auth.json

{
  "type": "scaffold",
  "args": {
    "backgroundColor": "#C0C0C0",
    "appBar": {
      "type": "app_bar",
      "args": {
        "backgroundColor": "#C0C0C0",
        "title": {
          "type": "text",
          "args": {
            "text": "User Login"
          }
        }
      }
    },
    "body": {
      "type": "padding",
      "args": {
        "padding": 25,
        "child": {
          "type": "center",
          "args": {
            "child": {
              "type": "column",
              "args": {
                "mainAxisAlignment": "center",
                "children": [
                  {
                    "type": "text",
                    "args": {
                      "text": "Welcome",
                      "style": {
                        "fontSize": 30,
                        "fontWeight": "bold"
                      }
                    }
                  },
                  {
                    "type": "sized_box",
                    "args": {
                      "height": 20.0
                    }
                  },
                  {
                    "type": "form",
                    "args": {
                      "child": {
                        "type": "column",
                        "args": {
                          "children": [
                            {
                              "type": "text_form_field",
                              "id": "user_email",
                              "args": {
                                "decoration": {
                                  "hintText": "Enter User Email....",
                                  "labelText": "User Email"
                                },
                                "validators": [
                                  {
                                    "type": "required"
                                  },
                                  {
                                    "type": "email"
                                  }
                                ]
                              }
                            },
                            {
                              "type": "sized_box",
                              "args": {
                                "height": 20.0
                              }
                            },
                            {
                              "type": "text_form_field",
                              "id": "user_password",
                              "args": {
                                "decoration": {
                                  "hintText": "Enter User password....",
                                  "labelText": "User Password"
                                },
                                "validators": [
                                  {
                                    "type": "required"
                                  }
                                ]
                              }
                            },
                            {
                              "type": "sized_box",
                              "args": {
                                "height": 30.0
                              }
                            },
                            {
                              "type": "elevated_button",
                              "id": "submit_button",
                              "args": {
                                "onPressed": "${validateForm('form_context')}",
                                "style": {
                                  "backgroundColor": "#0000FF"
                                },
                                "child": {
                                  "type": "save_context",
                                  "args": {
                                    "key": "form_context",
                                    "child": {
                                      "type": "text",
                                      "args": {
                                        "text": "Login",
                                        "style": {
                                          "fontSize": 25,
                                          "color": "#FFFFFF",
                                          "fontWeight": "bold"
                                        }
                                      }
                                    }
                                  }
                                }
                              }
                            }
                          ]
                        }
                      }
                    }
                  }
                ]
              }
            }
          }
        }
      }
    }
  }
}
jpeiffer commented 4 months ago

I'm not entirely sure I'm understanding the question. Also, would you mind edititing your comment to use the triple backtick so that it formats correctly? It's hard to read as-is.

vijaymsc commented 3 months ago

I need dynamically register registerFunctions based json, example if i add new button in my widget json file my onpressed function also add dynamically in registerFunctions .

crisperit commented 3 months ago
  1. You can define set of validators - https://github.com/peiffer-innovations/form_validation, use them like that: https://github.com/peiffer-innovations/json_dynamic_widget/blob/main/json_dynamic_widget/example/assets/pages/form.json#L208-L215 and mostly depends on bool valid = Form.of(context).validate();

  2. You can pass all variables in a list and create a dynamic logic which creates the body from them and send to your server

vijaymsc commented 3 months ago

Thanks for your response, but I need to add a new button in my json at the time my newly added button onTap function is not registered in my live app or apk, so give an error because of function not registered . That's why I'm asking that registerFunctions also dynamically register. I don't know if this is possible; if possible, please guide me.  @crisperit @jpeiffer

crisperit commented 2 months ago

You can call registerFunctions whenever you want async

I guess the main problem is that your functions and views that they need to handle are too coupled.

I think that you should have a single, generic function that just receives all variables via the args like validateForm('form_context',['user_email','user_password']) and convert it to some json body and send to the server for the validation.

It is worth also to consider https://github.com/peiffer-innovations/json_dynamic_widget_plugin_js which sort of is giving possibility to "generate" functions on the view side. You can inject some JS code as a function via the view