Skip to content

Instantly share code, notes, and snippets.

@ayoubzulfiqar
Last active February 8, 2022 16:56
Show Gist options
  • Save ayoubzulfiqar/b6a5828f3095d97b6f3fd1442390a440 to your computer and use it in GitHub Desktop.
Save ayoubzulfiqar/b6a5828f3095d97b6f3fd1442390a440 to your computer and use it in GitHub Desktop.
These are the basic methods to call api in dart
// The main maethod (just return the widget name to fetch the data from different methods)
import 'package:flutter/material.dart';
import 'package:flutterx/demo.dart';
import 'package:flutterx/photos.dart';
void main() {
runApp(const Experiment());
}
class Experiment extends StatelessWidget {
const Experiment({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
// in home property of material you can use User() for user data or Photo to get photo data from second method
home: Photos(),
);
}
}
// Method one with Example of getting user data (simple and easy)
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Users extends StatefulWidget {
const Users({Key? key}) : super(key: key);
@override
State<Users> createState() => _Users();
}
class _Users extends State<Users> {
getUserData() async {
const String url = 'https://jsonplaceholder.typicode.com/users';
var response = await http.get(Uri.parse(url));
var jsonData = jsonDecode(response.body);
List<User> users = [];
for (var u in jsonData) {
User user = User(u['name'], u['username'], u['email']);
users.add(user);
}
// print(users.length);
return users;
}
@override
Widget build(BuildContext context) {
return SafeArea(
top: false,
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.grey,
elevation: 0.0,
title: const Text('Fetch data'),
),
body: Card(
child: FutureBuilder(
future: getUserData(),
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return const Center(
child: Text('Loading......'),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Container(
padding: const EdgeInsets.only(
top: 10, left: 15, right: 10, bottom: 10),
margin:
const EdgeInsets.only(top: 10, left: 10, right: 10),
decoration: BoxDecoration(
color: Colors.grey.withOpacity(0.3),
borderRadius: BorderRadius.circular(5)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
snapshot.data[index].name,
style: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
const SizedBox(height: 5),
Text(
snapshot.data[index].username,
style: const TextStyle(fontSize: 16),
),
const SizedBox(height: 5),
Text(snapshot.data[index].email),
],
),
);
},
);
}
},
),
),
),
);
}
}
class User {
// int id;
String name;
String username;
String email;
// String city;
User(
this.name,
this.username,
// this.city,
this.email,
);
}
// Method two for getting api data as referred in documentation (for multiple values and testable)
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Products extends StatefulWidget {
const Products({Key? key}) : super(key: key);
@override
State<Products> createState() => _ProductsState();
}
class _ProductsState extends State<Products> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Products'),
),
body: FutureBuilder(
future: fetchProducts(http.Client()),
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return Center(
child: Text('Something Spooky '),
);
} else if (snapshot.hasData) {
return ProductList(items: snapshot.data);
} else {
return CircularProgressIndicator();
}
},
),
);
}
}
Future<List<Items>> fetchProducts(http.Client client) async {
final response =
await client.get(Uri.parse("https://fakestoreapi.com/products"));
return compute(parseProducts, response.body);
}
List<Items> parseProducts(String responseBody) {
final parsed = jsonDecode(responseBody);
return parsed.map<Items>((json) => Items.fromJson(json)).toList();
}
class Items {
int id;
String title;
double price;
String category;
String imgUrl;
Items({
required this.id,
required this.title,
required this.price,
required this.category,
required this.imgUrl,
});
factory Items.fromJson(Map<String, dynamic> json) {
return Items(
id: json['id'] as int,
title: json['title'] as String,
price: json['price'] * 1.0,
category: json['category'] as String,
imgUrl: json['image'] as String,
);
}
}
class ProductList extends StatelessWidget {
const ProductList({Key? key, required this.items}) : super(key: key);
final List<Items> items;
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return Container(
padding: const EdgeInsets.all(20),
margin: const EdgeInsets.all(20),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(items[index].id.toString()),
Image.network(items[index].imgUrl),
Text(
items[index].title,
style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
),
Text(
items[index].price.toString(),
style: TextStyle(fontSize: 20),
),
Text(
items[index].category,
style: TextStyle(fontSize: 20),
),
],
),
);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment