Categories:
Flutter #102: Flutter HTTP Request (POST) | Fetch Records from MySQL with PHP API | Future Builder

Flutter HTTP Request (POST) | Fetch Records from MySQL with PHP API | Future Builder. Copy and paste the below code as per your requirements.

pubspec.yaml

http: ^0.13.4 #to interact with api
fluttertoast: ^8.0.9 #to display toast message

Dashboard.dart

import 'package:flutter/material.dart';

import 'blogdata.dart';

class DashBoard extends StatelessWidget {
  const DashBoard({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Dashboard'),),
      body: Center(child: FlatButton(
        color: Colors.teal,
        textColor: Colors.white,
        onPressed: () {
          Navigator.of(context).push(MaterialPageRoute(builder: (context)=>UserBlog()));
        },
        child: const Text('GO TO BLOG'),
      ),),
    );
  }
}

blogdata.dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
class UserBlog extends StatefulWidget {
  @override
  _UserBlogState createState() => _UserBlogState();
}
class _UserBlogState extends State<UserBlog>  {
  late List blogdata;
  Future<String> getBlogData() async {
    var response = await http.post(Uri.http("192.168.0.104", '/login/blogdata.php', {'q': '{http}'}));
    setState(() {
      blogdata = json.decode(response.body);
    });
    return "Success!";
  }

  @override
  void initState(){
    getBlogData();
  }
  @override
  void dispose() {
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Blog'),),
      body: FutureBuilder<String>(
          future:  getBlogData(),
          builder: (context, AsyncSnapshot<String> snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(
                itemCount: blogdata == null ? 0 : blogdata.length,
                itemBuilder: (BuildContext context, int index){
                  return Card(
                    clipBehavior: Clip.antiAlias,
                    child: Column(
                      children: [
                        ListTile(
                          leading: null,
                          title: Text(blogdata[index]["title"],style: const TextStyle(color: Colors.deepOrangeAccent,fontSize: 20),),
                          subtitle: Text(blogdata[index]["content"],style: const TextStyle(color: Colors.black,fontSize: 15),),
                        ),
                      ],
                    ),
                  );
                },
              );
            } else {
              return Center(
                child: Container(),
              );
            }
          }
      ),
    );
  }
}

blogdata.php

<?php
$db = mysqli_connect('localhost','root','','userdata');
if(!$db)
{
	echo "Database connection failed";
}
$data = mysqli_query($db,"select * from blog");
$rows = array();
while($r = mysqli_fetch_assoc($data))
{
	$rows[] = $r;
}
print json_encode($rows);
?>

No responses yet

Leave a Reply

Your email address will not be published.