简体   繁体   中英

why is not inserted in flutter

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


?>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM