Home > Enterprise >  Expected a value of type int but got one of type String
Expected a value of type int but got one of type String

Time:11-01

I have been trying to post request usisng http package in flutter. There are 4 fields I am trying to send post request. Here is my controller code:


  Future<bool> createDisplay(
      String name, String category, String templateName, int productId) async {
    var url = Uri.parse(
        "https://digital-display.betafore.com/api/v1/digital-display/displays/");
    var token = localStorage.getItem('access');
    try {
      // var formdata = new Map<String, dynamic>();
      // formdata["name"] = name;
      // formdata["category"] = category;
      // formdata["template_name"] = templateName;
      // formdata["products"] = 1;

      var formdata = {
        "name": name,
        "category": category,
        "template_name": templateName,
        "products[0]": productId,
      };

      http.Response response =
          await http.post(url, body: json.encode(formdata), headers: {
        "Content-Type": "application/json",
        'Authorization':
            'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjY3MjMzNjEzLCJpYXQiOjE2NjcxNDcyMTMsImp0aSI6IjgyNDg0YWYzMDdmOTQ0YjNhMTQ5ZWIzN2NkNjIzNGI4IiwiaWQiOjV9.qc9fmF4B0V6NTwxsztBb6AkF78kU_06wommCa5gLgOo'
      });
      Future.error(response.body);
      var data = json.encode(response.body) as FormData;
      if (response.statusCode == 200) {
        print(response.body);
        return Future.error("Its working");
      } else {
        return Future.error("Code Proble");
      }
    } catch (exception) {
      Future.error("Something is wrong with the codes");
      return false;
    }
  }

Here is the form and code where I try to pass the value. Here is the var types. As you can see I took _product as Integer but still I am getting string.


`String _name = "";`
`String _category = "";`
`String _templateName = "";`
`late final int _product;`

final _form = GlobalKey<FormState>();

  void _addDisplay() async {
    var isValid = _form.currentState!.validate();
    if (!isValid) {
      return;
    }
    _form.currentState!.save();
    bool create = await Provider.of<DisplayController>(context, listen: false)
        .createDisplay(_name, _category, _templateName, _product);
    if (create) {
      showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: Text("Created"),
              actions: [
                ElevatedButton(
                  child: const Text("Return"),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          });
    } else {
      showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: Text("Failed to create display!"),
              actions: [
                ElevatedButton(
                  child: const Text("Return"),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          });
    }
  }

  Here is front end code:  

       Flexible(
                            child: Padding(
                              padding: EdgeInsets.all(10),
                              child: TextFormField(
                                keyboardType: TextInputType.number,
                                validator: (v) {
                                  if (v!.isEmpty) {
                                    return "Please enter valid product Id";
                                  } else {
                                    return null;
                                  }
                                },
                                onSaved: (value) {
                                  _product = value as int;
                                },
                                autofocus: true,
                                style: const TextStyle(
                                    fontSize: 15.0, color: Colors.black),
                                decoration: InputDecoration(
                                  border: InputBorder.none,
                                  hintText: 'Product Id',
                                  filled: true,
                                  fillColor: Colors.white,
                                  contentPadding: const EdgeInsets.only(
                                      left: 14.0, bottom: 6.0, top: 8.0),
                                  focusedBorder: OutlineInputBorder(
                                    borderSide: const BorderSide(
                                        color: Color.fromARGB(255, 73, 57, 55)),
                                    borderRadius: BorderRadius.circular(0.0),
                                  ),
                                  enabledBorder: UnderlineInputBorder(
                                    borderSide:
                                        const BorderSide(color: Colors.grey),
                                    borderRadius: BorderRadius.circular(0.0),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],

So, Here I try to pass the int value and I also took int type. But still I am getting this error I mentioned above.

I tried to pass name, tamplatename and category as string but I tool int type of productId as I attached my code there you can see I tool int type productId. Then in the create display page I also took late final int \_product. In the onSaved function I tried this:

onSaved: (value) {_product = value as int;} still getting error is there a way to solve this issue?

CodePudding user response:

Use int.parse(value) will fix the issue.

onSaved: (value) {_product = int.parse(value);}

CodePudding user response:

I'd go for a safer option and use tryParse with a default value if the text isn't an int.

I.e.

onSaved: (value) => _product = int.tryParse(value) ?? 0,

Or handle the possible null return value from tryParse in a different way that seems fit for your application.

  • Related