API Data Fetching and Display in Flutter

 



import 'dart:convert';

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

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

@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.red
),
home: Api(),
);
}
}


class Api extends StatefulWidget {
const Api({super.key});

@override
State<Api> createState() => _ApiState();
}

class _ApiState extends State<Api> {

User? userData;

var userId;
var id;
var title;

Future<void> getData()async{
final url = "https://jsonplaceholder.typicode.com/albums/1";
final response = await http.get(Uri.parse(url));
print(response.body);
if(response.statusCode == 200){
var responseData = json.decode(response.body);
userId = responseData["userId"].toString();
id = responseData["id"].toString();
title = responseData["title"].toString();
print(userId.toString());
print(id.toString());
print(title.toString());
setState(() {
});
}
}

Future<void> fetchData1() async {
final url = "https://jsonplaceholder.typicode.com/albums/1";
final response = await http.get(Uri.parse(url));

if (response.statusCode == 200) {
User user = User.fromJson(json.decode(response.body));
setState(() {
userData = user;
});
} else {
throw Exception('Failed to load data');
}
}

Future<Map<String, dynamic>> fetchData2() async {
final url = "https://jsonplaceholder.typicode.com/albums/1";
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to load data');
}
}

Future<User> fetchData() async {
final url = "https://jsonplaceholder.typicode.com/albums/1";
final response = await http.get(Uri.parse(url));

if (response.statusCode == 200) {
// Parse JSON response into User object
return User.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load data');
}
}




@override
void initState() {
// TODO: implement initState
super.initState();
//fetchData();

}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Api Demo"),
),
// body: Column(
// children: [
// Text(userId),
// Text(title),
// Text(id),
// ],
// ),


// body: Center(
// child: userData == null
// ? CircularProgressIndicator() // Show loading indicator while fetching data
// : Column(
// mainAxisAlignment: MainAxisAlignment.center,
// children: <Widget>[
// Text(
// 'userId: ${userData!.userId}',
// style: TextStyle(fontSize: 18),
// ),
// Text(
// 'id: ${userData!.id}',
// style: TextStyle(fontSize: 18),
// ),
// Text(
// 'title: ${userData!.title}',
// style: TextStyle(fontSize: 18),
// ),
// ],
// ),
// ),

// body: FutureBuilder(
// future: fetchData(),
// builder: (BuildContext context, AsyncSnapshot<Map<String, dynamic>> snapshot) {
// if (snapshot.connectionState == ConnectionState.waiting) {
// return CircularProgressIndicator(); // Show loading indicator
// } else if (snapshot.hasError) {
// return Text('Error: ${snapshot.error}');
// } else {
// // Data loaded successfully
// var data = snapshot.data!;
// return Column(
// mainAxisAlignment: MainAxisAlignment.center,
// children: <Widget>[
// Text(
// 'userId: ${data['userId']}',
// style: TextStyle(fontSize: 18),
// ),
// Text(
// 'id: ${data['id']}',
// style: TextStyle(fontSize: 18),
// ),
// Text(
// 'title: ${data['title']}',
// style: TextStyle(fontSize: 18),
// ),
// ],
// );
// }
// },
// ),


body: Center(
child: FutureBuilder<User>(
future: fetchData(),
builder: (BuildContext context, AsyncSnapshot<User> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator(); // Show loading indicator
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else if (!snapshot.hasData) {
return Text('No Data');
} else {
// Data loaded successfully
User user = snapshot.data!;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'userId: ${user.userId}',
style: TextStyle(fontSize: 18),
),
Text(
'id: ${user.id}',
style: TextStyle(fontSize: 18),
),
Text(
'title: ${user.title}',
style: TextStyle(fontSize: 18),
),
],
);
}
},
),
),
);
}
}


class User {
int? userId;
int? id;
String? title;

User({this.userId, this.id, this.title});

User.fromJson(Map<String, dynamic> json) {
userId = json['userId'];
id = json['id'];
title = json['title'];
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['userId'] = this.userId;
data['id'] = this.id;
data['title'] = this.title;
return data;
}
}


Comments

Popular posts from this blog

Unlocking the Power of OOP: A Beginner's Guide to Objects, Encapsulation, Inheritance, Abstraction, and Polymorphism

HTTP GET Response in Flutter

Building a Flutter Firebase Firestore CRUD App