Flutter Fake API
1. On file main.dart
import 'package:crud_api/models/post_model.dart';
import 'package:crud_api/screens/create_post.dart';
import 'package:crud_api/services/post_service.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Home(),
);
}
}
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
final PostService postService = PostService();
refreshData() async {
postService.getAllPost();
}
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CreatePostScreen(),
),
).then((value) {
setState(() {
refreshData();
});
});
},
),
appBar: AppBar(
title: Text("Home"),
),
body: FutureBuilder<List<PostModel>?>(
future: postService.getAllPost(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
final data = snapshot.data![index];
print(data.id);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CreatePostScreen(
id: data.id,
title: data.title,
body: data.body,
image_url: data.imageUrl,
),
),
);
},
child: Card(
child: ListTile(
title: Text(snapshot.data![index].title!),
subtitle: Text(snapshot.data![index].body!),
leading: Image.network(
snapshot.data![index].imageUrl!,
fit: BoxFit.cover,
),
trailing: TextButton(
onPressed: () {
postService
.deletePost(snapshot.data![index].id!);
setState(() {
postService.getAllPost();
});
},
child: Text("Delete"))),
),
);
},
);
}
return Center(
child: Text("Something went wrong"),
);
},
));
}
}
2. lib/services/post_service.dart
import 'package:crud_api/models/post_model.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class PostService {
Future<List<PostModel>?> getAllPost() async {
var url = Uri.parse('http://localhost:3000/posts');
try {
var response = await http.get(url);
List lstPosts = json.decode(response.body);
print("lst post $lstPosts");
List<PostModel> posts = [];
lstPosts.forEach((post) {
posts.add(PostModel.fromJson(post));
});
return posts;
} catch (ex) {
print(ex);
return null;
}
}
Future createPost(String title, String body, String imageUrl) async {
var url = Uri.parse('http://localhost:3000/posts');
try {
Map map = {'body': body, 'title': title, 'image_url': imageUrl};
print(json.encode(map));
var header = {"Content-Type": "application/json"};
var response =
await http.post(url, body: json.encode(map), headers: header);
if (response.statusCode == 200) {
return "created succesfully";
} else {
return "unable to create data";
}
} catch (ex) {
print("error :$ex");
}
}
Future<String> deletePost(int id) async {
var url = Uri.parse('http://localhost:3000/posts/$id');
try {
var response = await http.delete(url);
if (response.statusCode == 200) {
return "delete success";
} else {
return "delete fail";
}
} catch (ex) {
print("error : $ex");
return "${ex}";
}
}
Future updatePost(int id, String title, String body, String imageUrl) async {
var url = Uri.parse('http://localhost:3000/posts/$id');
var header = {"Content-Type": "application/json"};
Map map = {'body': body, 'title': title, 'image_url': imageUrl};
try {
var response = await http.put(url, body: map);
if (response.statusCode == 200) {
return "updated succesfully";
} else {
return "unable to update data";
}
} catch (ex) {
print("error : $ex");
return "${ex}";
}
}
}
3. lib/screens/create_post.dart
import 'package:crud_api/models/post_model.dart';
import 'package:crud_api/services/post_service.dart';
import 'package:flutter/material.dart';
class CreatePostScreen extends StatefulWidget {
final int? id;
final String? title;
final String? body;
final String? image_url;
CreatePostScreen({this.id, this.title, this.body, this.image_url});
@override
_CreatePostScreenState createState() => _CreatePostScreenState();
}
class _CreatePostScreenState extends State<CreatePostScreen> {
TextEditingController titleController = TextEditingController();
TextEditingController bodyController = TextEditingController();
TextEditingController imageController = TextEditingController();
final PostService postService = PostService();
@override
void initState() {
if (widget.id != null) {
titleController.text = widget.title!;
bodyController.text = widget.body!;
imageController.text = widget.image_url!;
}
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context, true);
},
),
title: Text("Create Post"),
),
body: Padding(
padding: EdgeInsets.all(20),
child: ListView(
children: [
TextField(
controller: titleController,
decoration: InputDecoration(hintText: "Title"),
),
TextField(
controller: bodyController,
decoration: InputDecoration(hintText: "Body"),
),
TextField(
controller: imageController,
decoration: InputDecoration(hintText: "Image Url "),
),
Row(
children: [
Expanded(
child: TextButton(
onPressed: () {
final title = titleController.text;
final body = bodyController.text;
final imageUrl = imageController.text;
print(body);
if (widget.id != null) {
postService.updatePost(
widget.id!, title, body, imageUrl);
} else {
postService.createPost(title, body, imageUrl);
}
},
child: Text("Save"),
),
),
],
),
],
),
),
);
}
}
4. lib/models/post_model.dart
class PostModel {
int? id;
String? title;
String? body;
String? imageUrl;
String? author;
PostModel(
{this.id,
required this.title,
required this.body,
required this.imageUrl,
required this.author});
PostModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
body = json['body'];
imageUrl = json['image_url'];
author = json['author'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['title'] = this.title;
data['body'] = this.body;
data['image_url'] = this.imageUrl;
data['author'] = this.author;
return data;
}
}