http error flutter code example
Example 1: Flutter not getting all data from api
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:clickmeetplay/iam/user/postbean.dart';
import 'package:http/http.dart' as http;
class PostHome extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(body: PostScreen(),),);
}
}
class PostScreen extends StatefulWidget {
@override
_PostScreenState createState() => _PostScreenState();
}
class _PostScreenState extends State {
List _postList =new List();
Future > fetchPost() async {
final response =
await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
List values=new List();
values = json.decode(response.body);
if(values.length>0){
for(int i=0;i map=values[i];
_postList .add(Post.fromJson(map));
debugPrint('Id-------${map['id']}');
}
}
}
return _postList;
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
@override
Widget build(BuildContext context) {
return Container();
}
@override
void initState() {
fetchPost();
}
}
Example 2: how to perform get request in flutter
import 'package:http/http.dart' as http;
import 'dart:convert';
class API
{
//replace with your endpoint
static String BASE_URL = 'https://some-url/api/';
static Future> getRequest() async {
Response res = await http.get(BASE_URL+'example');
if (res.statusCode == 200) {
List body = jsonDecode(res.body);
// complete by parsing the json body return into ExampleData object and return
//.................
}
}
}