E / flutter(16663):[错误:flutter / lib / ui / ui_dart_state.cc(177)]未处理的异常:FormatException:意外的字符(在字符33处)

时间:2020-10-18 06:23:50

标签: php flutter dart

我正在创建Flutter应用,并且试图将数据插入数据库中。我试图解决错误。但我找不到错误。为此,我从应用程序连接到服务器上的.php文件。但是我在Android Studio中看到了异常。

这是我的飞镖文件。

颤振:

import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;

class Register extends StatefulWidget {
  Register() : super();
  @override
  _RegisterState createState() => _RegisterState();
}

class _RegisterState extends State<Register>{

  TextEditingController voterIdCTRL, usernameCTRL, nameCTRL, passwordCTRL,
      confirm_passCTRL, emailCTRL, ageCTRL, phone_numCTRL;
  @override
  void initState(){
    super.initState();
      voterIdCTRL = new TextEditingController();
      usernameCTRL = new TextEditingController();
      nameCTRL = new TextEditingController();
      passwordCTRL = new TextEditingController();
      confirm_passCTRL = new TextEditingController();
      emailCTRL = new TextEditingController();
      ageCTRL = new TextEditingController();
      phone_numCTRL = new  TextEditingController();
  }


  Future registerUser() async{
    var theUrl = 'http://192.168.0.158/fyp_db/register.php';
    var input = {
      "voter_id" : voterIdCTRL.text,
      "username" : usernameCTRL.text,
      "name" : nameCTRL.text,
      "password" : passwordCTRL.text,
      "confirm_password" : confirm_passCTRL.text,
      "email" : emailCTRL.text,
      "age" : ageCTRL.text,
      "phone_number" : phone_numCTRL.text,
    };

    var response = await http.post(theUrl, body: input);

    //String data = json.decode(response.body);
    if(jsonDecode(response.body.toString()) == "Account already exists!"){
      Fluttertoast.showToast(
          msg: "Username Exists. Please try again!",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0
      );
    }else{
      if(jsonDecode(response.body.toString()) == "Success"){
        Fluttertoast.showToast(
            msg: "Register Successful!",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            fontSize: 16.0
        );
      }else {
        Fluttertoast.showToast(
            msg: "Error, Please try again!",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.green,
            textColor: Colors.white,
            fontSize: 16.0
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        resizeToAvoidBottomPadding: false,
        body: ListView(
          // crossAxisAlignment: CrossAxisAlignment.start,
            padding: EdgeInsets.all(15),
            children: <Widget>[
              Container(
                child: Stack(
                  children: <Widget>[
                    Container(
                      padding: EdgeInsets.fromLTRB(15.0, 110.0, 0.0, 0.0),
                      child: Text(
                        'Create An',
                        style:
                        TextStyle(fontSize: 50.0, fontWeight: FontWeight.bold),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.fromLTRB(15.0, 170.0, 0.0, 0.0),
                      child: Text(
                        'New Account',
                        style:
                        TextStyle(fontSize: 50.0, fontWeight: FontWeight.bold),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.fromLTRB(315.0, 170.0, 0.0, 0.0),
                      child: Text(
                        '.',
                        style: TextStyle(
                            fontSize: 50.0,
                            fontWeight: FontWeight.bold,
                            color: Colors.indigoAccent),
                      ),
                    )
                  ],
                ),
              ),
              Container(
                  padding: EdgeInsets.only(top: 35.0, left: 20.0, right: 20.0),
                  child: Column(
                    children: <Widget>[
                      TextField(
                        controller: voterIdCTRL,
                        decoration: InputDecoration(
                            labelText: 'VOTER ID',
                            labelStyle: TextStyle(
                                fontFamily: 'Montserrat',
                                fontWeight: FontWeight.bold,
                                color: Colors.grey),
                            focusedBorder: UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.indigoAccent))),
                      ),
                      SizedBox(height: 10.0),
                      TextField(
                        controller:  usernameCTRL,
                        decoration: InputDecoration(
                            hintText: 'Username',
                            labelText: 'USERNAME',
                            labelStyle: TextStyle(
                                fontFamily: 'Montserrat',
                                fontWeight: FontWeight.bold,
                                color: Colors.grey),
                            focusedBorder: UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.indigoAccent))),
                      ),
                      SizedBox(height: 10.0),
                      TextField(
                        controller: nameCTRL,
                        decoration: InputDecoration(
                            hintText: 'Name',
                            labelText: 'NAME',
                            labelStyle: TextStyle(
                                fontFamily: 'Montserrat',
                                fontWeight: FontWeight.bold,
                                color: Colors.grey),
                            focusedBorder: UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.indigoAccent))),
                      ),
                      SizedBox(height: 10.0),
                      TextField(
                        controller: passwordCTRL,
                        decoration: InputDecoration(
                            hintText: 'Password',
                            labelText: 'PASSWORD',
                            labelStyle: TextStyle(
                                fontFamily: 'Montserrat',
                                fontWeight: FontWeight.bold,
                                color: Colors.grey),
                            focusedBorder: UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.indigoAccent))),
                        obscureText: true,
                      ),
                      SizedBox(height: 10.0),
                      TextField(
                        controller:  confirm_passCTRL,
                        decoration: InputDecoration(
                            hintText: 'Confirm Password',
                            labelText: 'CONFIRM PASSWORD ',
                            labelStyle: TextStyle(
                                fontFamily: 'Montserrat',
                                fontWeight: FontWeight.bold,
                                color: Colors.grey),
                            focusedBorder: UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.indigoAccent))),
                        obscureText: true,
                      ),
                      SizedBox(height: 10.0),
                      TextField(
                        controller: emailCTRL,
                        decoration: InputDecoration(
                            hintText: 'Email',
                            labelText: 'EMAIL',
                            labelStyle: TextStyle(
                                fontFamily: 'Montserrat',
                                fontWeight: FontWeight.bold,
                                color: Colors.grey),
                            focusedBorder: UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.indigoAccent))),
                      ),
                      SizedBox(height: 10.0),
                      TextField(
                        controller: ageCTRL,
                        decoration: InputDecoration(
                            hintText: 'Age',
                            labelText: 'AGE',
                            labelStyle: TextStyle(
                                fontFamily: 'Montserrat',
                                fontWeight: FontWeight.bold,
                                color: Colors.grey),
                            focusedBorder: UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.indigoAccent))),
                      ),
                      SizedBox(height: 10.0),
                      TextField(
                        controller:  phone_numCTRL,
                        decoration: InputDecoration(
                            hintText: 'Phone Number',
                            labelText: 'PHONE NUMBER',
                            labelStyle: TextStyle(
                                fontFamily: 'Montserrat',
                                fontWeight: FontWeight.bold,
                                color: Colors.grey),
                            focusedBorder: UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.indigoAccent))),
                      ),
                      SizedBox(height: 50.0),
                      Container(
                          height: 50.0,
                          child: Material(
                            borderRadius: BorderRadius.circular(30.0),
                            shadowColor: Colors.indigo,
                            color: Colors.indigoAccent,
                            elevation: 7.0,
                            child: MaterialButton(
                              onPressed: () => registerUser(),
                              child: Center(
                                child: Text(
                                  'REGISTER',
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold,
                                      fontFamily: 'Montserrat'),
                                ),
                              ),
                            ),
                          )),
                      SizedBox(height: 20.0),
                      Container(
                        height: 50.0,
                        color: Colors.transparent,
                        child: Container(
                          decoration: BoxDecoration(
                              border: Border.all(
                                  color: Colors.black,
                                  style: BorderStyle.solid,
                                  width: 1.0),
                              color: Colors.transparent,
                              borderRadius: BorderRadius.circular(30.0)),
                          child: InkWell(
                            onTap: () {
                              Navigator.of(context).pop();
                            },
                            child:
                            Center(
                              child: Text('Go Back',
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontFamily: 'Montserrat')),
                            ),
                          ),
                        ),
                      ),
                      SizedBox(height: 30.0),
                    ],
                  )),
            ]));
  }
}

这些是我的.PHP文件。

PHP: connection.php

<?php
$dbserver = "localhost";
$username = "root";
$password = "";
$dbname = "fypdb";

    // Create connection
    //$conn = new PDO('mysql:host=localhost;dbname=fypdb', $username, $password);
    $connect = new mysqli($dbserver, $username, $password, $dbname);

    if($connect){
        echo json_encode('Connected successfully');
    }else{
        echo $exc -> getMessage();
    die("Connection failed : " . $conn -> connect_error);
    }
?>

register.php

<?php

require("connection.php");

$voter_id = $_POST["voter_id"];
$username = $_POST["username"];
$password = $_POST["password"];
$confirm_password = $_POST["confirm_password"];
$email = $_POST["email"];
$age = $_POST["age"];
$name = $_POST["name"];
$phone_number = $_POST["phone_number"];
$profile_pic = $_POST["profile_pic"];

$query = "SELECT * FROM voter_profile WHERE email = '$email'";

$res = mysqli_query($connect,$query);

$data = mysqli_fetch_array($res);

if($data[0] > 1){
    echo json_encode("Account already exists!");
}else{
    $query = "INSERT INTO voter_profile(voter_id, username, password, confirm_password, email, age, name, phone_number, profile_pic) 
                VALUES ('$voter_id', '$username', '$password', '$confirm_password', '$email', '$age', '$name', '$phone_number', NULL)";
    $res = mysqli_query($query);

    if($res){
        echo json_encode("Success");
    }else{
        echo json_encode("Error");
    }
}

?>

错误:

E/flutter (16663): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: FormatException: Unexpected character (at character 25)
E/flutter (16663): "Connected successfully"<br />
E/flutter (16663):                         ^
E/flutter (16663): 
E/flutter (16663): #0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1404:5)
E/flutter (16663): #1      _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:934:48)
E/flutter (16663): #2      _parseJson (dart:convert-patch/convert_patch.dart:40:10)
E/flutter (16663): #3      JsonDecoder.convert (dart:convert/json.dart:505:36)
E/flutter (16663): #4      JsonCodec.decode (dart:convert/json.dart:156:41)
E/flutter (16663): #5      jsonDecode (dart:convert/json.dart:96:10)
E/flutter (16663): #6      _RegisterState.registerUser (package:test_app/register.dart:47:8)
E/flutter (16663): <asynchronous suspension>
E/flutter (16663): #7      _RegisterState.build.<anonymous closure> (package:test_app/register.dart:237:48)
E/flutter (16663): #8      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:993:19)
E/flutter (16663): #9      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1111:38)
E/flutter (16663): #10     GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:183:24)
E/flutter (16663): #11     TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:598:11)
E/flutter (16663): #12     BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:287:5)
E/flutter (16663): #13     BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:259:7)
E/flutter (16663): #14     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:157:27)
E/flutter (16663): #15     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:362:20)
E/flutter (16663): #16     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:338:22)
E/flutter (16663): #17     RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:267:11)
E/flutter (16663): #18     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:295:7)
E/flutter (16663): #19     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:240:7)
E/flutter (16663): #20     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:213:7)
E/flutter (16663): #21     _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter (16663): #22     _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter (16663): #23     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter (16663): #24     _invoke1 (dart:ui/hooks.dart:265:10)
E/flutter (16663): #25     _dispatchPointerDataPacket (dart:ui/hooks.dart:174:5)
E/flutter (16663): 

2 个答案:

答案 0 :(得分:1)

您需要将input编码为json

var input = {
      "voter_id" : voterIdCTRL.text,
      "username" : usernameCTRL.text,
      "name" : nameCTRL.text,
      "password" : passwordCTRL.text,
      "confirm_password" : confirm_passCTRL.text,
      "email" : emailCTRL.text,
      "age" : ageCTRL.text,
      "phone_number" : phone_numCTRL.text,
    };

    // Here is important
    var body = json.encode(input);

    var response = await http.post(theUrl, body: body); 

您可以从official document中阅读更多内容。

答案 1 :(得分:0)

下面的代码您的连接是成功的,它不是数组对象 json_encode 解码函数仅用于 aaray 对象,因此删除 joson_encode 和 flutter 文件删除 json_decode....

<?php
$dbserver = "localhost";
$username = "root";
$password = "";
$dbname = "fypdb";

    // Create connection
    //$conn = new PDO('mysql:host=localhost;dbname=fypdb', $username, $password);
    $connect = new mysqli($dbserver, $username, $password, $dbname);

    if($connect){
        echo('Connected successfully');
    }else{
        echo $exc -> getMessage();
    die("Connection failed : " . $conn -> connect_error);
    }
?>