Parse was a popular backend service managed by Facebook until the tech giant stopped its services in 2017. However, one can still make use of their SDKs and libraries provided for range of platforms like Android, IOS to name a few, provided they setup their own server or use Back4App.
In this example, we will be using Back4App which makes use of Parse framework to provide backend services. There is one problem though that there is no official SDK for Flutter unlike other platforms but Back4app provides RESTful APIs for communicating with our backend.
Parse console for your project.
3. You should then see a console like the one shown above.
4. On the left side you can see a section named Database Browser which lists all the classes currently present in your database. By default there are two classes present namely Role and User. Create a new class named Todo
which will store the data for each Todo item.
5. You can then proceed to add a column named task to the class which will store the actual task.
Go ahead and create a new Flutter project.
Clear your main.dart
and paste the code below so that we are on the same page.
import 'package:flutter/material.dart';
import 'package:todo_app/ui/todo_screen.dart';
void main() {
runApp(TodoApp());
}
class TodoApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: TodoScreen(),
);
}
}
Create a package named ui inside the lib folder. Inside the ui package, create a dart file named todo_screen.dart
and paste the below starter code into it.
import 'package:flutter/material.dart';
class TodoScreen extends StatefulWidget {
@override
_TodoScreenState createState() => _TodoScreenState();
}
class _TodoScreenState extends State<TodoScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Todo Screen"),
),
);
}
}
Create a constants.dart
file inside lib folder where we’ll be declaring some credentials like ApplicationId and RestApiKey which we’ll be using to communicate with our backend while working with our REST APIs.
<span id="ed3e" class="jn id dt ar jj b ew jo jp r jq">_const_ **kParseApplicationId** = "Your Parse Application Id goes here";
_const_ **kParseRestApiKey** = "Your Parse Rest API key goes here";</span>
Go ahead and create a package named model inside lib folder.
Inside this package create a model class named todo.dart
which we’ll be using to store our “todo”. Paste the below code into it.
// To parse this JSON data, do
//
// final todo = todoFromJson(jsonString);
import 'dart:convert';
List<Todo> todoFromJson(String str) => List<Todo>.from(json.decode(str).map((x) => Todo.fromJson(x)));
String todoToJson(List<Todo> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Todo {
String objectId;
String task;
Todo({
this.objectId,
this.task,
});
factory Todo.fromJson(Map<String, dynamic> json) => Todo(
objectId: json["objectId"],
task: json["task"],
);
Map<String, dynamic> toJson() => {
"objectId": objectId,
"task": task,
};
}
Todo model class
The above class was generated using quicktype.io where you paste the json schema and it generates you a model class for your preferred language.
We’ve setup our model and ui package. Now before we setup our network_utils package, we need to add a dependency named http which is used for making http requests in Flutter. I assume you know how to add dependency to your pubspec.yaml so I’ll skip this part for brevity.
Now create a package named network_utils inside your lib folder. Insisde this folder, create a class named todo_utils.dart
which will handle all the network calls.
In this app, we’ll be doing four basic database operations namely CRUD (Create, Read, Update, Delete). So the basic skeleton of our todo_utils.dart
keeping the operations to be performed will be like following:
import 'dart:convert';
import 'package:http/http.dart';
import 'package:todo_app/model/todo.dart';
import 'package:todo_app/constants.dart';
class TodoUtils {
//Create
static addTodo(Todo todo) {
}
//Read
static getTodoList() {
}
//Update
static updateTodo(Todo todo) {
}
//Delete
static deleteTodo(String objectId) {
}
}
Let’s finish up all the functions one by one before we move onto the UI part and then eventually call these functions there.
For adding Todo lets update our addTodo()
to the following
class TodoUtils {
static final String _baseUrl = "https://parseapi.back4app.com/classes/";
static Future<Response> addTodo(Todo todo) async{
String apiUrl = _baseUrl + "Todo";
Response response = await post(apiUrl,
headers: {
'X-Parse-Application-Id' : kParseApplicationId,
'X-Parse-REST-API-Key' : kParseRestApiKey,
'Content-Type' : 'application/json'
},
body: json.encode(todo.toJson()),
);
return response;
}
}
Let me explain this function in brief as the same format would be seen for the rest of the functions which we’ll cover
__baseUrl_
holds the url part common to all the APIs where as apiUrl
is the actual API url for adding a Todo item to database.post()
function from the [http](https://pub.dev/packages/http#-installing-tab-)
package and we are passing certain headers to this function which we had declared in our constants.dart
which are used used for authentication.todo.toJson()
using json.encode()
from dart:convert
library.Similarly, lets update the rest of the functions namely
getTodoList()
updateTodo()
deleteTodo()
import 'dart:convert';
import 'package:http/http.dart';
import 'package:todo_app/model/todo.dart';
import 'package:todo_app/constants.dart';
class TodoUtils {
static final String _baseUrl = "https://parseapi.back4app.com/classes/";
//CREATE
static Future<Response> addTodo(Todo todo) async{
String apiUrl = _baseUrl + "Todo";
Response response = await post(apiUrl,
headers: {
'X-Parse-Application-Id' : kParseApplicationId,
'X-Parse-REST-API-Key' : kParseRestApiKey,
'Content-Type' : 'application/json'
},
body: json.encode(todo.toJson()),
);
return response;
}
//READ
static Future getTodoList() async{
String apiUrl = _baseUrl + "Todo";
Response response = await get(apiUrl, headers: {
'X-Parse-Application-Id' : kParseApplicationId,
'X-Parse-REST-API-Key' : kParseRestApiKey,
});
return response;
}
//UPDATE
static Future updateTodo(Todo todo) async{
String apiUrl = _baseUrl + "Todo/${todo.objectId}";
Response response = await put(apiUrl, headers: {
'X-Parse-Application-Id' : kParseApplicationId,
'X-Parse-REST-API-Key' : kParseRestApiKey,
'Content-Type' : 'application/json',
},
body: json.encode(todo.toJson())
);
return response;
}
//DELETE
static Future deleteTodo(String objectId) async{
String apiUrl = _baseUrl + "Todo/$objectId";
Response response = await delete(apiUrl, headers: {
'X-Parse-Application-Id' : kParseApplicationId,
'X-Parse-REST-API-Key' : kParseRestApiKey,
});
return response;
}
}
Now we’ll proceed with the final part which is creating a UI and calling those functions which we just created.
Let’s add the code for getting the list of all the todo items from the db and displaying it on the screen. So go to your todo_screen.dart
and update the code as below.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:todo_app/model/todo.dart';
import 'package:todo_app/network_utils/todo_utils.dart';
class TodoScreen extends StatefulWidget {
@override
_TodoScreenState createState() => _TodoScreenState();
}
class _TodoScreenState extends State<TodoScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text("Todo Screen"),
),
body: Container(
child: FutureBuilder(builder: (context, snapshot) {
if (snapshot.data != null) {
List<Todo> todoList = snapshot.data;
return ListView.builder(itemBuilder: (_, position) {
return ListTile(
title: Text(todoList[position].task),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(icon: Icon(Icons.edit), onPressed: () {
//Show dialog box to update item
}),
IconButton(icon: Icon(Icons.check_circle, color: Colors.green,), onPressed: () {
//Show dialog box to delete item
})
],
),
);
},
itemCount: todoList.length,
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
future: getTodoList(),
),
),
);
}
Future <List<Todo>> getTodoList() async{
List<Todo> todoList = [];
Response response = await TodoUtils.getTodoList();
print("Code is ${response.statusCode}");
print("Response is ${response.body}");
if (response.statusCode == 200) {
var body = json.decode(response.body);
var results = body["results"];
for (var todo in results) {
todoList.add(Todo.fromJson(todo));
}
} else {
//Handle error
}
return todoList;
}
}
So a function named getTodoList()
is added which is resonsible for getting the list of todos from the server and parsing the data back from json to our model class Todo
.
And a FutureBuilder
is used to build the UI as the items will be returned in future after the request is completed. Till then we should show a progress bar on the screen.
Go ahead and give it a run to see our list of todo items.
Todo Screen
Well that is because we haven’t added any yet and to add we’ll need to build functionality of add Todo first.
Go ahead and add a FloatingActionButton
to your Scaffold
on the tap of which we’ll be showing an AlertDialog
to enter the Todo.
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text("Todo Screen"),
),
body: Container(
child: FutureBuilder(builder: (context, snapshot) {
if (snapshot.data != null) {
List<Todo> todoList = snapshot.data;
return ListView.builder(itemBuilder: (_, position) {
return ListTile(
title: Text(todoList[position].task),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(icon: Icon(Icons.edit), onPressed: () {
}),
IconButton(icon: Icon(Icons.check_circle, color: Colors.green,), onPressed: () {
})
],
),
);
},
itemCount: todoList.length,
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
future: getTodoList(),
),
),
floatingActionButton: FloatingActionButton(onPressed: () {
},
child: Icon(Icons.add),
),
);
}
Updated Scaffold
Inside the onPressed()
we are going to call a function which will show user an AlertDialog
to enter a new Todo item.
Before that, let’s create a global TextEditingController
instance for accepting todos written by the user in AlertDialog
TextEditingController _taskController = TextEditingController();
void showAddTodoDialog() {
showDialog(context: context,
builder: (_) => AlertDialog(
content: Container(
width: double.maxFinite,
child: TextField(
controller: _taskController,
decoration: InputDecoration(
labelText: "Enter task",
),
),
),
actions: <Widget>[
FlatButton(onPressed: () {
Navigator.pop(context);
addTodo();
}, child: Text("Add")),
FlatButton(onPressed: () {
Navigator.pop(context);
}, child: Text("Cancel")),
],
)
);
}
void addTodo() {
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Row(
children: <Widget>[
Text("Adding task"),
CircularProgressIndicator(),
],
mainAxisAlignment: MainAxisAlignment.spaceBetween,
),
duration: Duration(minutes: 1),
));
Todo todo = Todo(task: _taskController.text);
TodoUtils.addTodo(todo)
.then((res) {
_scaffoldKey.currentState.hideCurrentSnackBar();
Response response = res;
if (response.statusCode == 201) {
//Successful
_taskController.text = "";
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Todo added!"), duration: Duration(seconds: 1),));
setState(() {
//Update UI
});
}
});
}
So there are two new functions written inside todo_screen.dart
namely showAddTodoDialog()
and addTodo()
for showing an AlertDialog
to accept Todo and adding a Todo item to database respectively.
Call the showAddTodoDialog()
inside the onPressed()
of our FloatingActionButton
.
floatingActionButton: FloatingActionButton(onPressed: () {
showAddTodoDialog();
},
child: Icon(Icons.add),
),
Adding Todo
Once a Todo has been added, usershould also be able to update it. For that we’ll again show an AlertDialog
with a TextField
showing the existing value of the Todo. And the user can then update the Todo to whatever they want and then tap on Update button.
We’ll again be writing two functions named showUpdateDialog(Todo todo)
and updateTodo()
for showing AlertDialog
for updating existing Todo and updating Todo in database respectively.
void showUpdateDialog(Todo todo) {
_taskController.text = todo.task;
showDialog(context: context,
builder: (_) => AlertDialog(
content: Container(
width: double.maxFinite,
child: TextField(
controller: _taskController,
decoration: InputDecoration(
labelText: "Enter updated task",
),
),
),
actions: <Widget>[
FlatButton(onPressed: () {
Navigator.pop(context);
todo.task = _taskController.text;
updateTodo(todo);
}, child: Text("Update")),
FlatButton(onPressed: () {
Navigator.pop(context);
}, child: Text("Cancel")),
],
)
);
}
void updateTodo(Todo todo) {
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text("Updating todo"),
CircularProgressIndicator(),
],
),
duration: Duration(minutes: 1),
),);
TodoUtils.updateTodo(todo)
.then((res) {
_scaffoldKey.currentState.hideCurrentSnackBar();
Response response = res;
if (response.statusCode == 200) {
//Successfully Deleted
_taskController.text = "";
_scaffoldKey.currentState.showSnackBar(SnackBar(content: (Text("Updated!"))));
setState(() {
});
} else {
//Handle error
}
});
}
Call the showUpdateTodoDialog(Todo todo)
inside the onPressed()
of edit icon button.
return ListTile(
title: Text(todoList[position].task),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(icon: Icon(Icons.edit), onPressed: () {
showUpdateDialog(todoList[position]);
}),
IconButton(icon: Icon(Icons.check_circle, color: Colors.green,), onPressed: () {
//Call function to delete todo
})
],
),
);
Update Todo
We are almost done with our Todo app. We are just left with delete functionality. So let’s go do it.
For deleting a todo, we’ll simply call a function to delete our Todo to keep this article short and to the point. (You can obviosly go ahead and show a confirmation dialog if you want)
void deleteTodo(String objectId) {
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text("Deleting todo"),
CircularProgressIndicator(),
],
),
duration: Duration(minutes: 1),
),);
TodoUtils.deleteTodo(objectId)
.then((res) {
_scaffoldKey.currentState.hideCurrentSnackBar();
Response response = res;
if (response.statusCode == 200) {
//Successfully Deleted
_scaffoldKey.currentState.showSnackBar(SnackBar(content: (Text("Deleted!")),duration: Duration(seconds: 1),));
setState(() {
});
} else {
//Handle error
}
});
}
Call the deleteTodo(String objectId)
function inside the onPressed()
of the delete button.
return ListTile(
title: Text(todoList[position].task),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(icon: Icon(Icons.edit), onPressed: () {
showUpdateDialog(todoList[position]);
}),
IconButton(icon: Icon(Icons.check_circle, color: Colors.green,), onPressed: () {
deleteTodo(todoList[position].objectId);
})
],
),
);
Deleting Todos
So that is it. We’ve successfully built a Todo app using Parse. The source code is available on my Github
I hope you enjoyed this article, if so feel free to clap as many times you wish.
Thank you for reading!
#flutter #parse #restful apis