Flutter Show Records From MYSQL Database
By Webotapp Academy•
<!-- wp:paragraph -->\n<p>In order to do it we have to follow a series of steps:</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">First, let us create a new table in our database called state</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>\n\nCREATE TABLE IF NOT EXISTS state (\n id INT PRIMARY KEY,\n state_name TEXT DEFAULT NULL\n);\n\n// Add Some Records Manually\n</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">Second, we will create the API PHP file for fetching the states</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code><?php\ninclude('cors.php');\ninclude('../database.php');\n\n// Assuming you have already established a PDO database connection in database.php\n// Replace database credentials with your own.\n\nheader('Content-Type: application/json');\n\n// Initialize an empty response array.\n$response = array();\n\n// Check if the request is a GET request.\nif ($_SERVER['REQUEST_METHOD'] === 'GET') {\n // Get the mobile number from the query parameters.\n \n\n // Create a SQL query to fetch orders by mobile number.\n $sql = \"SELECT * FROM state \";\n $stmt = $conn->prepare($sql);\n \n\n if ($stmt->execute()) {\n // Fetch the orders and add them to the response.\n $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);\n $response['success'] = true;\n $response['message'] = \"Orders fetched successfully.\";\n $response['data'] = $orders;\n } else {\n $response['success'] = false;\n $response['message'] = \"Error: \" . $stmt->errorInfo();\n }\n} else {\n $response['success'] = false;\n $response['message'] = \"Invalid request method.\";\n}\n\n// Output the response as JSON.\necho json_encode($response);\n?>\n</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">Third we will create the function in our flutter app</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code> Future<void> _FetchState() async {\n \n try {\n final response = await http.get(Uri.parse('https://aboutassam.in/flutter_app/api/fetch_state.php'));\n if (response.statusCode == 200) {\n final responseData = json.decode(response.body);\n if (responseData['success'] == true) {\n setState(() {\n // Extract state names from the response data\n List<String> stateNames = [];\n List<dynamic> data = responseData['data'];\n for (var state in data) {\n stateNames.add(state['state_name']);\n }\n // Update the StateName variable with the list of state names\n StateName = stateNames.join(', '); // Example: \"State1, State2, State3\"\n \n });\n } else {\n throw Exception(responseData['message']);\n }\n } else {\n throw Exception('Failed to load orders');\n }\n } catch (e) {\n print('Error fetching state names: $e');\n }\n }</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">Fourth, we will apply the function in our UI.</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code> Container(\n margin: const EdgeInsets.all(6.0),\n decoration: BoxDecoration(\n border: Border.all(color: Colors.grey), // Adjust border properties as needed\n borderRadius: BorderRadius.circular(5.0), // Optional: Add border radius\n ),\n child: DropdownButtonFormField<String>(\n value: StateName.isNotEmpty ? null : '',\n hint: Text('Select State'),\n items: StateName.isNotEmpty\n ? StateName.split(', ').map((String state) {\n return DropdownMenuItem<String>(\n value: state,\n child: Text(state),\n );\n }).toList()\n : [],\n onChanged: (String? newValue) {\n // Handle state selection here\n },\n ),\n ),</code></pre>\n<!-- /wp:code -->