Home > Software design >  Exception has occurred. _CastError (type 'TextEditingController' is not a subtype of type
Exception has occurred. _CastError (type 'TextEditingController' is not a subtype of type

Time:12-31

Help me Error Exception has occurred

class AddProduct extends StatelessWidget {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();
  final TextEditingController _priceController = TextEditingController();
  final TextEditingController _imageUrlController = TextEditingController();
  Future saveProduct() async {
    final response =
        await http.post(Uri.parse("http://127.0.0.1:8000/api/products"), body: {
      "name": _nameController,
      "description": _descriptionController,
      "price": _priceController,
      "image_url": _imageUrlController
    });
  }

How can i fix this ? Thanks

CodePudding user response:

The only way you can get the text from a TextEditingController is to insert the get method .text at the end of your Controller, with that in mind, your code should be something like this:

class AddProduct extends StatelessWidget {

final _formKey = GlobalKey<FormState>();
final TextEditingController _nameController = TextEditingController();
final TextEditingController _descriptionController = TextEditingController();
final TextEditingController _priceController = TextEditingController();
final TextEditingController _imageUrlController = TextEditingController();

Future saveProduct() async {
  final response = await http.post(Uri.parse("http://127.0.0.1:8000/api/products"), 
  body: {
    "name": _nameController.text,
    "description": _descriptionController.text,
    "price": _priceController.text,
    "image_url": _imageUrlController.text
    });
}

Note that it's a good idea to check if your input fields are not null, unless for some reason, you don't care if your user send some empty data.

  • Related