Uncategorized

Fetching Data From PHP API to Flutter App

Import Packages

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
  • material.dart: Provides Material Design widgets. Reference Link
  • convert: Allows you to convert between different data representations like JSON to Map. Reference Link
  • http: Used for making HTTP requests. Reference Link
class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

StatefulWidget: A widget that can change over time.

class _HomeState extends State<Home> {
  Map<String, dynamic>? productData;
  • _HomeState: The mutable state for the Home widget.
  • productData: A map to hold the product data fetched from the API.
  @override
  void initState() {
    super.initState();
    fetchProduct();
  }

initState(): Called when the State object is created. We use it to call fetchProduct().

  fetchProduct() async {
    final response = await http.get(Uri.parse('http://booppers.tk/api/fetch_product.php'));
    if (response.statusCode == 200) {
      setState(() {
        productData = json.decode(response.body);
      });
    }
  }

fetchProduct(): Fetches product data from the API and updates productData.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // ... (Your UI code)
    );
  }
  • build(): Builds the UI. It returns a Scaffold widget, which is a basic layout structure.

Drawer and AppBar

Inside the Scaffold, you have an AppBar and a Drawer for navigation.

Leave a Reply

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