flutter 发生异常,_CastError(类型“TextEditingController”在类型转换中不是类型“String”的子类型)

p8h8hvxi  于 2023-01-02  发布在  Flutter
关注(0)|答案(1)|浏览(158)

帮助我错误发生异常

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
    });
  }

我该怎么做?谢谢

nfs0ujit

nfs0ujit1#

从TextEditingController获取文本的唯一方法是在Controller的末尾插入get方法.text,记住这一点,您的代码应该如下所示:

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
    });
}

请注意,检查输入字段是否不为空是一个好主意,除非出于某种原因,您不关心用户是否发送了一些空数据。

相关问题