As shown in the video tutorial, change your main.dart file to this
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State
List categories = []; // List to hold category data
String message = ''; // Variable to hold the "Hello John" message
@override
void initState() {
super.initState();
fetchCategories(); // Fetch categories when the app starts
}
// Function to fetch categories from the API
Future
var url = Uri.parse('http://localhost/fluttertest/api.php'); // Replace with your API URL
var response = await http.get(url);
if (response.statusCode == 200) {
setState(() {
categories = json.decode(response.body); // Decode the JSON data and store it
});
} else {
print('Failed to load categories');
}
}
// Function to update the message when the button is clicked
void showMessage() {
setState(() {
message = "Hello John"; // Update the message to display "Hello John"
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Categories List'),
),
body: Column(
children: [
// Display the "Hello John" message when the button is clicked
Container(
margin: EdgeInsets.only(top: 10),
child: Text('Ye mera div'),
),
Text(
message, // Display the current value of the message
style: TextStyle(fontSize: 24),
),
// Button to trigger the showMessage function
ElevatedButton(
onPressed: showMessage, // Call showMessage on button click
child: Text('Click Me'),
),
// Display categories fetched from the API
Expanded(
child: ListView.builder(
itemCount: categories.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(categories[index]['CategoryName']),
subtitle: Text(categories[index]['Description']),
);
},
),
),
],
),
);
}
}
Install xampp , create a folder in your htdocs , in that folder create api.php
connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Set headers to return JSON and allow CORS (if needed)
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
// SQL query to get categories
$sql = "SELECT CategoryID, CategoryName, Description FROM categories";
$result = $conn->query($sql);
$categories = array();
// Fetch the results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// Add each category to the array
$categories[] = $row;
}
// Output the array as JSON
echo json_encode($categories);
} else {
// If no records found, return an empty array
echo json_encode([]);
}
// Close the connection
$conn->close();
?>