0

Hey guys I have a problem when I press the insert ad I want the info about the book insert into the table but it shows me this error:

E/flutter ( 3974): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'TextEditingController' is not a subtype of type 'String' in type cast

I want if I press the button after I press the button insert the info into the table and I tried to make everything in the connection and the insert-ads.php nothing works

this is my code:

import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'dart:convert';

// ignore: library_prefixes

class uploudd extends StatefulWidget {
  const uploudd({key});

  @override
  State<uploudd> createState() => _uplouddState();
}

class _uplouddState extends State<uploudd> {
  File? _imagepath;
  String? _imageName;
  String? _imageData;
  var UnaverNAME;
  var CollegeName;
  var districts1;

  TextEditingController NameBook = TextEditingController();
  TextEditingController Email = TextEditingController();
  TextEditingController PhoNamber = TextEditingController();
  TextEditingController NotAds = TextEditingController();

  SizedBox TextF(var name, var exampel, var inText) {
    return SizedBox(
      width: 175,
      child: TextField(
        keyboardType: TextInputType.emailAddress,
        controller: inText,
        decoration: InputDecoration(
            filled: true,
            fillColor: Colors.white,
            labelText: "    $name   ",
            labelStyle: TextStyle(
                fontSize: 15,
                color: Color(0xffF4AC47),
                fontWeight: FontWeight.w700),
            hintText: "   $exampel ",
            suffix: Icon(
              Icons.person,
              size: 20,
              color: Colors.white,
            ),
            enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(15),
                borderSide: BorderSide(
                  color: Color(0xff072A52),
                  width: 4,
                )),
            focusedBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Color(0xff072A52), width: 4),
            )),
      ),
    );
  }

  Padding TextForm(var name, var exampel, var inText) {
    return Padding(
      padding: const EdgeInsets.all(13.0),
      child: TextField(
        maxLines: 5,
        keyboardType: TextInputType.emailAddress,
        controller: inText,
        decoration: InputDecoration(
            filled: true,
            fillColor: Colors.white,
            labelText: "    $name   ",
            labelStyle: TextStyle(
                fontSize: 35,
                color: Color(0xffF4AC47),
                fontWeight: FontWeight.w700),
            hintText: "   $exampel ",
            suffix: Icon(
              Icons.person,
              size: 20,
              color: Colors.white,
            ),
            enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(15),
                borderSide: BorderSide(
                  color: Color(0xff42A9D2),
                  width: 4,
                )),
            focusedBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Color(0xff42A9D2), width: 4),
            )),
      ),
    );
  }

  List<String> universities = [
    "جامعة الملك سعود",
    "جامعة الأميرة نورة ",
    "جامعة الإمام ",
    "جامعة الفيصل",
    "جامعة الفيصلية",
    "جامعة اليمامة",
    "جامعة عفت",
    "جامعة الفيصلية",
    "الكلية التقنية"
  ];

  SizedBox districtsINRiadh(
    String TitleName,
    var nameCo,
  ) {
    String selectItem = '$TitleName';
    return SizedBox(
      width: 186,
      child: Center(
        child: DropdownButtonFormField<String>(
          decoration: InputDecoration(
              focusedBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Color(0xff072A52), width: 4),
              ),
              enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12),
                  borderSide: BorderSide(
                    width: 4,
                    color: Color(0xff072A52),
                  ))),
          hint: Center(
              child: Text(
            "     $TitleName   ",
            // "   collage name",
            style: TextStyle(
                fontWeight: FontWeight.w800,
                fontSize: 15,
                color: Color(0xffF4AC47)),
          )),
          // value: selectItem,
          items: districtsInRiyadh
              .map((item) => DropdownMenuItem(
                  value: item,
                  child: Text(item,
                      style:
                          TextStyle(fontSize: 20, color: Color(0xffF4AC47)))))
              .toList(),
          onChanged: (value) {
            setState(() {
              // var finalname;
              selectItem = value!;

              districts1 = value;
              // print(CollegeName);
            });
          },
        ),
      ),
    );
  }

  SizedBox Universities(
    String TitleName,
    var nameCo,
  ) {
    String selectItem = '$TitleName';
    return SizedBox(
      width: 186,
      child: Center(
        child: DropdownButtonFormField<String>(
          decoration: InputDecoration(
              focusedBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Color(0xff072A52), width: 4),
              ),
              enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12),
                  borderSide: BorderSide(
                    width: 4,
                    color: Color(0xff072A52),
                  ))),
          hint: Center(
              child: Text(
            "     $TitleName   ",
            // "   collage name",
            style: TextStyle(
                fontWeight: FontWeight.w800,
                fontSize: 15,
                color: Color(0xffF4AC47)),
          )),
          // value: selectItem,
          items: universities
              .map((item) => DropdownMenuItem(
                  value: item,
                  child: Text(item,
                      style:
                          TextStyle(fontSize: 20, color: Color(0xffF4AC47)))))
              .toList(),
          onChanged: (value) {
            setState(() {
              // var finalname;
              selectItem = value!;

              CollegeName = value;
              // print(CollegeName);
            });
          },
        ),
      ),
    );
  }

  List<String> districtsInRiyadh = [
    "العزيزية",
    "الفاروق",
    "الحمراء",
    "المنصورة",
    "النهضة",
    "القويعية",
    "الربوة",
    "الروضة",
    "الشفاء",
    "اليرموك",
    "الرياض الجديدة",
    "الشهداء",
    "الزهراء",
    "الجزيرة",
    "الملك عبد الله",
    "الفيحاء",
    "النهضة ",
    "العليا",
    "المطار القديم",
    "السليمانية",
    "الثمامة",
    "الورود",
    "الياسمين"
  ];
  List<String> disciplines = [
    'الهندسة',
    'العلوم الطبيعية',
    'العلوم الاجتماعية',
    'العلوم الإنسانية',
    'العلوم الإدارية',
    'التربية',
    'الطب والعلوم الصحية',
    'القانون',
    'الفن والتصميم',
    'الزراعة والدراسات البيئية',
  ];

  SizedBox SectionName(
    String TitleName,
    var nameUnaverNAME,
  ) {
    String selectItem = '$TitleName';
    return SizedBox(
      width: 186,
      child: Center(
        child: DropdownButtonFormField<String>(
          decoration: InputDecoration(
              focusedBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Color(0xff072A52), width: 4),
              ),
              enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12),
                  borderSide: BorderSide(width: 4, color: Color(0xff072A52)))),

          hint: Center(
              child: Text(
            "     $TitleName   ",
            // "   collage name",
            style: TextStyle(
                fontWeight: FontWeight.w800,
                fontSize: 20,
                color: Color(0xffF4AC47)),
          )),
          // value: selectItem,
          items: disciplines
              .map((item) => DropdownMenuItem(
                  value: item,
                  child: Text(item,
                      style: TextStyle(
                          fontSize: 12,
                          color: Color(0xffF4AC47),
                          fontWeight: FontWeight.w900))))
              .toList(),
          onChanged: (value) {
            setState(() {
              selectItem = value!;
              UnaverNAME = value;
            });
          },
        ),
      ),
    );
  }

//------------This is get path images----------------
  final ImagePicker imagePicker = ImagePicker();

  Future<void> getimages() async {
    final XFile? getimage =
        await imagePicker.pickImage(source: ImageSource.gallery);

    //if (getimage == null) return;
    setState(() {
      //print(File(getimage.path));

      _imagepath = File(getimage!.path);
      _imageName = getimage.path.split('/').last;
      _imageData = base64Encode(_imagepath!.readAsBytesSync());
      print(_imagepath);
      print(_imageName);
      print(_imageData);
    });
  }

//--------------This is method is add images--------------------
  Future<void> upload() async {
    try {
      var url = "http://111111/php_file/UploadImage.php";
      var res = await http.post(Uri.parse(url), body: {
        "data": _imageData,
        "name": _imageName,
      });
      var response = jsonDecode(res.body);
      if (response['success'] == "true") {
        print("uploudd");
      } else
        print("no images");
    } catch (e) {
      print(e);
    }
    // if (_imagepath == null) return;
    // String imageCode = base64Encode(_imagepath!.readAsBytesSync());
    // String id = _imagepath!.path.split('/').last;

    // var response = await http.post(Uri.parse(url), body: {
    //   "id": id,
    //   "imageCode": imageCode,
    // });
    // var res = jsonDecode(response.body);
    // if (res['suvvess'] == "true") {
    //   print("uploudd");
    // } else
    //   print("no images");
  }

  Future InsertAdd() async {
    String TheUrl = "https://***.***.***.**/insert-ads.php";
    var rep = await http.post(Uri.parse(TheUrl), headers: {
      "Accept": "application/json"
    }, body: {
      "book_name": NameBook,
      "phone2": PhoNamber,
    });
    var respb = json.decode(rep.body);
    print(respb);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: SingleChildScrollView(
          child: Center(
            child: Column(
              children: [
                Container(
                  margin: EdgeInsets.only(right: 60, left: 70),
                  height: 54.0,
                  width: 224.0,
                  child: Container(
                      decoration: BoxDecoration(
                          border:
                              Border.all(color: Color(0xffF4AC47), width: 3),
                          color: Color(0xff42A9D2),
                          borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(40),
                              bottomRight: Radius.circular(40))),
                      child: const Center(
                        child: Text(
                          " insert ad",
                          style: TextStyle(
                              fontSize: 30,
                              color: Color(0xff072A52),
                              fontWeight: FontWeight.w700),
                          textAlign: TextAlign.center,
                        ),
                      )),
                ),
                SizedBox(
                  height: 30,
                ),
                Row(
                  children: [
                    SizedBox(
                      width: 304,
                    ),
                    Container(
                      child: Text(
                        "    images",
                        style:
                            TextStyle(color: Color(0xffF4AC47), fontSize: 25),
                      ),
                      decoration: BoxDecoration(
                          color: Color(0xff072A52),
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(60),
                            bottomLeft: Radius.circular(60),
                          )),
                    ),
                  ],
                ),
                Column(
                  children: [
                    Row(
                      children: [
                        Container(
                          height: 70,
                          width: 392,
                          child: Row(
                            children: [
                              SizedBox(
                                width: 208,
                              ),
                              Container(
                                height: 60,
                                width: 60,
                                child: _imagepath == null
                                    ? Text('not here in images')
                                    : Image.file(_imagepath!),
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(60),
                                  bottomLeft: Radius.circular(60),
                                )),
                              ),
                              SizedBox(
                                width: 40,
                              ),
                              Container(
                                child: IconButton(
                                  onPressed: getimages,
                                  icon: Icon(Icons.add),
                                  color: Colors.black,
                                  iconSize: 60,
                                ),
                              ),
                            ],
                          ),
                          decoration: BoxDecoration(
                              color: Colors.white,
                              border: Border.all(
                                color: Color(0xff42A9D2),
                                width: 2,
                              ),
                              borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(60),
                                bottomLeft: Radius.circular(60),
                              )),
                        ),
                      ],
                    ),
                  ],
                ),
                SizedBox(
                  height: 20,
                ),

                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Row(
                    children: [
                      Universities("   collage name", UnaverNAME),
                      SizedBox(
                        width: 15,
                      ),

                      TextF('      book name   ', 'prog101', NameBook),
                      //   SectionName(' spe', CollegeName),
                    ],
                  ),
                ),

                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Row(
                    children: [
                      SectionName(' spe', CollegeName),
                      SizedBox(
                        width: 15,
                      ),
                      TextF('       phone number   ', ' 0555511111', PhoNamber),
                    ],
                  ),
                ),
                SizedBox(
                  height: 15,
                ),
                districtsINRiadh('districts', districts1),

                TextForm(
                    '        comments in ads ',
                    'book for programing and for collage',
                    NotAds),
                SizedBox(
                  height: 30,
                ),

                ConstrainedBox(
                  constraints: BoxConstraints.tightFor(width: 385, height: 70),
                  child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                          primary: Color(0xff072A52),
                          shape: BeveledRectangleBorder(
                              borderRadius:
                                  BorderRadiusDirectional.circular(4))),
                      onPressed: () {
                          InsertAdd();
                        setState(() {
                          print(UnaverNAME);
                          print(CollegeName);
                          print(districts1);
                          print(NameBook.text.toString());
                          print(NotAds.text.toString());
                          print(PhoNamber.text);
                          // print(pass.text.toString());

                          //final Name = TextEditingController();
                        });
                        // Navigator.of(context).push(
                        //   MaterialPageRoute(
                        //     builder: (context) => welcome(
                        //         paswordd: pasword.text, uernamee: name.text)
                        //         )

                        //         );
                      },
                      child: Text(
                        "insert ad",
                        style: TextStyle(
                            color: Color(0xffF4AC47),
                            fontSize: 30,
                            fontWeight: FontWeight.w500),
                      )),
                ),

                // Container(
                //   child: ElevatedButton(
                //     child: Text('uplod'),
                //     onPressed: getimages,
                //   ),
                // ),
                // Center(
                //   child: _imagepath == null
                //       ? Text('not here in images')
                //       : Image.file(_imagepath!),
                // ),
                // Container(
                //   child: _imagepath == null
                //       ? Text('not images is here')
                //       : ElevatedButton(
                //           child: Text('print'),
                //           onPressed: upload,
                //         ),
                // ),

                //Image(image:Image.asset('name'));
              ],
            ),
          ),
        ),
      ),
    );
  }
}

this is my php code:

<?

require('config.php');
// insert a new ad

$book_name = $_POST['book_name'];
$phone = $_POST['phone2'];


$sql = "INSERT INTO ads (`book_name`,`phone2`)VALUE ('$book_name','$phone')";

$statement = $connect -> prepare($sql);

$statement -> execute();

    echo json_encode("done add");


?>
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
ayed
  • 1
  • 5
  • Which line of code throws the error? Is this huge pile of code really a [mre] of the issue? It seems like you're trying to use an object like it's a piece of text...that's about the best we can say until you are more specific. I would guess you need to get the value of the text within that editing control, rather than using the object which represents the whole control. – ADyson Jan 18 '23 at 12:58
  • P.S. **Warning:** Your PHP code is vulnerable to SQL Injection attacks. You should use prepared statements **and parameters** to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli / PDO. **Never** insert unparameterised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Jan 18 '23 at 12:59
  • https://phpdelusions.net/ also contains good examples of writing safe SQL using mysqlin and PDO. See also: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. You seem to have adopted prepared statements, but missed the vital step where you convert the injected variables into parameters instead. You need to finish the job. – ADyson Jan 18 '23 at 13:00

1 Answers1

1

You have to use textController's text property to find the text. You have already done it at several places but missed while making the request.

Future InsertAdd() async {
    String TheUrl = "https://***.***.***.**/insert-ads.php";
    var rep = await http.post(Uri.parse(TheUrl), headers: {
      "Accept": "application/json"
    }, body: {
      "book_name": NameBook.text.toString(),
      "phone2": PhoNamber.text.toString(),
    });
    var respb = json.decode(rep.body);
    print(respb);
  }
Rahul
  • 3,529
  • 1
  • 5
  • 19
  • its not work sir i don't know why i tried this code and its not working ``` Future InsertAdd() async { String TheUrl = "https://***.***.***.**/insert-ads.php"; var rep = await http.post(Uri.parse(TheUrl), headers: { "Accept": "application/json" }, body: { "book_name": NameBook.text.toString(), "phone2": PhoNamber.text.toString(), }); var respb = json.decode(rep.body); print(respb); } ``` – ayed Jan 19 '23 at 21:06