TEXT: HTTP GET WITH PARAMETERS - FLUTTER

 main.dart

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Sample API'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _msg = "Message From API";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: [
            const SizedBox(
              height: 30,
            ),
            Text(_msg),
            ElevatedButton(
              onPressed: () {
                getMessageFromAPI();
              },
              child: const Text(
                "Get Data",
              ),
            )
          ],
        ),
      ),
    );
  }

  void getMessageFromAPI() async {
    String url = "http://localhost/flutter/api/hello_api.php";

    final Map<String, dynamic> queryParans = {
      "name": "Donald Duck",
      "address": "Disney Land"
    };
    try {
      http.Response response =
          await http.get(Uri.parse(url).replace(queryParameters: queryParans));

      if (response.statusCode == 200) {
        setState(() {
          _msg = response.body;
        });
      } else {
        _msg = "${response.statusCode} ${response.reasonPhrase}";
      }
    } catch (error) {
      setState(() {
        _msg = "$error";
      });
    }
  }
}


 

API

hello_api.php

<?php
  header('Content-Type: application/json');
  header("Access-Control-Allow-Origin: *");

  $name = $_GET['name'];
  $address = $_GET['address'];

  echo "Hello $name, you are from $address!";

?>

 

 

No comments:

Post a Comment

IMAGE: CODE SPLITTING - USE COMPONENTS (NEXT JS)

 CONTACTS LIST (MAIN) contacts_list.js TEXT VERSION view.js update.js TEXT VERSION