1

I am fairly new to Flutter and would like to find out how to display MySQL query results based on the TextField value entered by user.

As I am new to Flutter I scraped bits and pieces from other Tutorials to try and achieve outcome .

Some help would be tremendously grateful for , as I am struggling for weeks now with this.This is a re-edit on my question as I am trying to be bit more descriptive hoping someone can pleeeease help . Thank you

This is my MySQL table : My MySQL table

This my PHP file (flutter_data.PHP)

$con = mysqli_connect($HostName, $HostUser, $HostPass, $DatabaseName);

$json = file_get_contents('php://input'); 

$obj = json_decode($json,true);

$name = $obj['name'];//this value coming from TextField ( i hope :-)) 

$CheckSQL = "SELECT * FROM Student_data WHERE student_name = '$name'";

$result = $con->query($CheckSQL);

if ($result->num_rows >0) {

 while($row[] = $result->fetch_assoc()) {

 $Item = $row;

 $json = json_encode($Item, JSON_NUMERIC_CHECK);

 }

}else {

 echo "No Results Found.";

}

echo $json;

$con->close();
?>

I did a test to see if my PHP file works without the WHERE clause . Below running my PHP file .

enter image description here

My Home screen consisting of TextField , Image , FlatButton

enter image description here

Setting Class variables:


 int studentID;
 String studentName;
 int studentPhoneNumber;
 String studentSubject;

  Studentdata({
    this.studentID,
    this.studentName,
    this.studentPhoneNumber,
    this.studentSubject
  });

  factory Studentdata.fromJson(Map<String, dynamic> json) {
    return Studentdata(
      studentID: json['id'],
      studentName: json['student_name'],
      studentPhoneNumber: json['student_phone_number'],
      studentSubject: json['student_class']

    );
  }
}

I have set my TextField to capture onChanged value

 onChanged: (value) {

                setState(() {

                    name = value;

My FlatButton with onPressed :

onPressed: () {


                  var route = new MaterialPageRoute(

                    builder: (BuildContext context) => new NextPageState(name.toString(),                           


                  ));
                  Navigator.of(context).push(route);
                },

Below code for NextPage :

class NextPageState extends StatefulWidget {

  final String name;

  NextPageState(this.name);

  @override

  State<StatefulWidget> createState() {

    return NextPage(this.name);

  }
}

class NextPage extends State<NextPageState> {

  final String name ;

  NextPage(this.name);

  // API URL
  var url = 'https://www.datashine.co.za/flutter_data.php';

  Future<List<Studentdata>> fetchStudent() async {

    var data = {'name': name};

    var response = await http.post(url, body: json.encode(data));

    if (response.statusCode == 200) {

      print(response.statusCode);

      final items = json.decode(response.body).cast<Map<String, dynamic>>();

      List<Studentdata> studentList = items.map<Studentdata>((json) {
        return Studentdata.fromJson(json);
      }).toList();

      return studentList;

      }

    else {
      throw Exception('Failed to load data from Server.');
    }
  }

  @override
Widget build(BuildContext context) {
  return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(name),
          automaticallyImplyLeading: true,
          leading: IconButton(icon:Icon(Icons.arrow_back),
          onPressed:() => Navigator.pop(context, false),
        )
      ),
      body: FutureBuilder<List<Studentdata>>(
      future: fetchStudent(),
      builder: (context, snapshot) {

      if (!snapshot.hasData) return Center(
        child: CircularProgressIndicator()
      );

        return ListView(
      children: snapshot.data
      .map((data) => Column(children: <Widget>[

        GestureDetector(
          onTap: (){print(data.studentName);},
          child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [

          Padding(
          padding: EdgeInsets.fromLTRB(0, 20, 0, 10),
          child: Text('Name = ' + data.studentName.toString(),
            style: TextStyle(fontSize: 21))),



                  ]),)
                 ],))
           .toList(),
              );
             },
            )
          ));
         }
        }

Upon running App , it seems like no results are returning . So I have no idea on how to fix . The Circularprogress indicator just loads and hangs .

enter image description here

Garth
  • 123
  • 1
  • 11
  • I have implemented similar things. I was storing the textFieldValue in a variable based on onValueChanged parameter of textField in a variable, at the time of button press, I was passing that variable to the next screen, and in init state of the second screen, I was firing data base query. this query will return a list and store it in the appropriate variable, set it in listViewBuilder as per requirement. Hope this logic will work for you. – Sanket Vekariya Mar 22 '20 at 09:00
  • @Sanket Vekariya Any chance I could have a visual on what you've done . As I am fairly new to flutter I wiill better understand by working thru an example code – Garth Mar 22 '20 at 09:07
  • Sorry currently it is not possible to share otherwise I would have shared already. You can give a try to implement this. If you face any issue with this, you can comment here for any help. :) – Sanket Vekariya Mar 22 '20 at 09:10
  • @Sanket Vekariya . Thanks . Ohk . I will try and implement . I will document and post progress . Thank you – Garth Mar 22 '20 at 09:15
  • @SanketVekariya I have re-edited my Question . I face some issues and am commenting for help . Please can you HELP :-) – Garth Apr 06 '20 at 18:38
  • Well it seems like there is a issue from my PHP generated Json file , because when I use a test Json file , I get a result – Garth Apr 08 '20 at 16:03
  • I have referred this while implementation. https://medium.com/@santosenoque.ss/how-to-connect-flutter-app-to-mysql-web-server-and-phpmyadmin-e100f47bfb82 – Sanket Vekariya Apr 08 '20 at 16:39
  • @SanketVekariya FINALLY I GOT IT WORKING !!! Made a few minor changes ,and now I am able to pull records from my own MySQL DB based on value user enters in TextField . Thanks for posting initial logic – Garth Apr 09 '20 at 17:23

0 Answers0