- Import Required Packages:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:carousel_slider/carousel_slider.dart';
These lines import the necessary packages for building a Flutter app with HTTP requests and image carousels.
- Create a StatefulWidget:
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
State<Home> createState() => _HomeState();
}
This defines a Flutter StatefulWidget
called Home
.
- Define the
_HomeState
Class:
class _HomeState extends State<Home> {
List<String> images = [];
String productName = '';
String productDescription = '';
@override
void initState() {
super.initState();
fetchData();
}
// Rest of the code...
}
In _HomeState
, we initialize three variables: images
for storing image URLs, productName
for the product title, and productDescription
for the product description. The initState
method is called when the widget is first created, and it invokes fetchData()
to retrieve data from the API.
- Fetch Data from API:
fetchData() async {
final response = await http.get(Uri.parse('https://booppers.tk/api/fetch_product.php'));
if (response.statusCode == 200) {
var data = json.decode(response.body);
setState(() {
images = [
'https://booppers.tk/uploads/' + data['pro_img_1'],
'https://booppers.tk/uploads/' + data['pro_img_2'],
'https://booppers.tk/uploads/' + data['pro_img_3']
];
productName = data['pro_name'];
productDescription = data['pro_desc'];
});
}
}
The fetchData
function makes an HTTP GET request to the specified API endpoint and processes the response. It extracts image URLs, product name, and product description, storing them in the corresponding variables.
- Build the Flutter UI:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// App bar configuration...
),
body: SingleChildScrollView(
child: Column(
children: [
// Carousel for images...
// Display Product Title and Description...
// Rest of the UI...
],
),
),
);
}
This is the main UI structure of the app. It includes an app bar, a carousel for displaying product images, and a section for showing the product title and description.
- Display Product Title and Description:
// Display Product Title and Description
Container(
margin: EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Product Title:',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
SizedBox(height: 10),
Text(
productName,
style: TextStyle(fontSize: 16),
),
SizedBox(height: 20),
Text(
'Product Description:',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
SizedBox(height: 10),
Text(
productDescription,
style: TextStyle(fontSize: 16),
),
],
),
),
In this section, we use a Container
to display the product title and description. The title is displayed with a larger font and bold text, followed by the product description.