Home > Software engineering >  How PHP return value fetch from flutter
How PHP return value fetch from flutter

Time:07-23

I have this simple php file

<?php

$arrA = array("name" => "Adam", "age" => "25");

$jasonValue =json_encode($arrA);
return $jasonValue;

i was wondering is there a way to fetch this return value as a json code in flutter? output should be like

{"name":"Adam", "age":"25"}

Here is waht i did but it did not work

 var url = Uri.http('path_to_my_php_file.php');
 var response = await http.get(url);    

    if (response.statusCode == 200) {       
       Map data = json.decode(response.body);
       print(data);
    } else {
      print('Something wents wrong');
    }

CodePudding user response:

I think you should use https, it's useless because streamResponse is used in http flutter. For example:

import 'package:http/http.dart' as https;
import 'dart:convert';

Future<void> _fetchData() async {
    var url = Uri.parse('path_to_my_php_file.php');
    final response = await https.get(url);    
    
    if (response.statusCode == 200) {
      var body = json.decode(response.body);
      print(body);
    } else {
      print("Something went wrong");
    }
}

or http

import 'package:http/http.dart' as http;
import 'dart:convert';

Future<void> _fetchData() async {
  var url = Uri.http('path_to_my_php_file.php');
  var request = http.Request('GET', url);

  http.StreamedResponse response = await request.send();

  if (response.statusCode == 200) {
    print(await response.stream.bytesToString());
  }else {
    print(response.reasonPhrase);
  }
}

CodePudding user response:

Just use http: ^0.13.4

final response = await http.post(url, body: body);

if (response.statusCode == 200) {
   final body = json.decode(response.body);
   print(body.toString);
}

Output :

  {
     "name":"Adam",
      "age":"25"
   }
  • Related