Uncategorized

Flutter Show Records From MYSQL Database

In order to do it we have to follow a series of steps:

First, let us create a new table in our database called state



CREATE TABLE IF NOT EXISTS state (
    id INT AUTO_INCREMENT PRIMARY KEY,
    state_name TEXT DEFAULT NULL
);

// Add Some Records Manually

Second, we will create the API PHP file for fetching the states

<?php
include('cors.php');
include('../database.php');

// Assuming you have already established a PDO database connection in database.php
// Replace database credentials with your own.

header('Content-Type: application/json');

// Initialize an empty response array.
$response = array();

// Check if the request is a GET request.
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Get the mobile number from the query parameters.
    

    // Create a SQL query to fetch orders by mobile number.
    $sql = "SELECT * FROM state ";
    $stmt = $conn->prepare($sql);
     

    if ($stmt->execute()) {
        // Fetch the orders and add them to the response.
        $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $response['success'] = true;
        $response['message'] = "Orders fetched successfully.";
        $response['data'] = $orders;
    } else {
        $response['success'] = false;
        $response['message'] = "Error: " . $stmt->errorInfo();
    }
} else {
    $response['success'] = false;
    $response['message'] = "Invalid request method.";
}

// Output the response as JSON.
echo json_encode($response);
?>

Third we will create the function in our flutter app

  Future<void> _FetchState() async {
    
    try {
      final response = await http.get(Uri.parse('https://aboutassam.in/flutter_app/api/fetch_state.php'));
      if (response.statusCode == 200) {
        final responseData = json.decode(response.body);
        if (responseData['success'] == true) {
          setState(() {
            // Extract state names from the response data
            List<String> stateNames = [];
            List<dynamic> data = responseData['data'];
            for (var state in data) {
              stateNames.add(state['state_name']);
            }
            // Update the StateName variable with the list of state names
            StateName = stateNames.join(', '); // Example: "State1, State2, State3"
            
          });
        } else {
          throw Exception(responseData['message']);
        }
      } else {
        throw Exception('Failed to load orders');
      }
    } catch (e) {
      print('Error fetching state names: $e');
    }
  }

Fourth, we will apply the function in our UI.

 Container(
                margin: const EdgeInsets.all(6.0),
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey), // Adjust border properties as needed
                  borderRadius: BorderRadius.circular(5.0), // Optional: Add border radius
                ),
                child: DropdownButtonFormField<String>(
                  value: StateName.isNotEmpty ? null : '',
                  hint: Text('Select State'),
                  items: StateName.isNotEmpty
                      ? StateName.split(', ').map((String state) {
                    return DropdownMenuItem<String>(
                      value: state,
                      child: Text(state),
                    );
                  }).toList()
                      : [],
                  onChanged: (String? newValue) {
                    // Handle state selection here
                  },
                ),
              ),

Leave a Reply

Your email address will not be published. Required fields are marked *