OndrejKunc / flutter_dynamic_forms

A collection of flutter and dart libraries allowing you to consume complex external forms at runtime.
MIT License
204 stars 60 forks source link

How to parse strings to integer/double for arithmetic expressions #89

Open tochiedev opened 3 years ago

tochiedev commented 3 years ago

Hi, Thanks for this package. Has been very useful in my project. I'm stuck on trying to get simple arithmetic expressions to work.

Here's my json:

{
    "@name": "form",
    "id": "form1",
    "children": [
        {
            "@name": "textField",
            "id": "amount",
            "label": "Amount",
            "hint": "Enter Amount",
            "inputType": "money"
        },
        {
            "@name": "textField",
            "id": "amount2",
            "label": "Amount2",
            "hint": "Enter Amount 2",
            "inputType": "money"
        },
        {
            "@name": "label",
            "id": "total",
            "value": {
                "expression": "(@amount + @amount2)"
            }
        }
    ]
}

I'm trying to add the values of the inputs e.g 5 +6 = 11, but it gives me 5+6 = 56. Could you kindly point me in the right direction?

Also, is there a way to get the value of a sibling form element from inside the renderer class of another element?

Thanks

OndrejKunc commented 3 years ago

Hi @tochiedev , About your first question: Right now there is no expression like stringToInt that would just convert String to number so the + operator just concatenates strings. Right now I am working on an injectable expression mechanism, so it would be easy to implement those expressions by yourself without modifying the library, but it is not finished yet. However, there is a better solution. The problem with the textField is that it has a value property which is of type String so it doesn't work with numbers very well. I would recommend writing your own component similar to textField, which will have value property of type int instead of String so you won't need to care about this conversion in expressions.

About the sibling question: Most of the time I use the id of the elements to reference them, but if you need something advanced, you can use the element parameter on the renderer to browse the structure of your model tree. For example, if you are in the renderer of the textField in your example, then you can get all the children of the current form like this: var children = (element.parent as Form).children; You can then find your desired child in this list.

Hope this helps.