Skip to content

Commit

Permalink
Added API integration support
Browse files Browse the repository at this point in the history
Signed-off-by: Tiago Góes <[email protected]>
  • Loading branch information
tiagodread committed Sep 2, 2024
1 parent b99742d commit 206ba1b
Show file tree
Hide file tree
Showing 11 changed files with 236 additions and 125 deletions.
2 changes: 1 addition & 1 deletion lib/constants/colors.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@ class AppColors {
}

const AppColors();
}
}
4 changes: 2 additions & 2 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:todo/repositories/sqlite_task_repository.dart';
import 'package:todo/repositories/api_task_repository.dart';
import 'package:todo/screens/home_screen.dart';

void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(ChangeNotifierProvider(
create: (context) => SQLiteTaskRepository(),
create: (context) => APITaskRepository(),
child: const App(),
));
}
Expand Down
30 changes: 28 additions & 2 deletions lib/models/task.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import 'package:json_annotation/json_annotation.dart';
import 'package:uuid/uuid.dart';

part 'task.g.dart';

@JsonSerializable()
class Task {
String id;
String title;
Expand All @@ -19,11 +23,33 @@ class Task {
this.rewardInSatoshis = 0,
}) : id = id ?? const Uuid().v4();

Map<String, dynamic> toMap() {
factory Task.fromJson(Map<String, dynamic> json) {
return Task(
id: json['id']?.toString(), // Convert int to String if necessary
title: json['title'] as String,
description: json['description'] as String,
createdAt: DateTime.parse(json['created_at'] as String),
isCompleted: json['is_completed'] as bool,
rewardInSatoshis: json['reward_in_satoshis'] ?? 0,
);
}

Map<String, dynamic> toJson() {
return {
'id': id,
'title': title,
'description': description,
'created_at': createdAt.toIso8601String(),
'is_completed': isCompleted,
'reward_in_satoshis': rewardInSatoshis,
};
}

Map<String, dynamic> toMap() {
return {
'id': id.toString(),
'title': title,
'description': description,
'createdAt': createdAt.toIso8601String(),
'completedAt': completedAt?.toIso8601String(),
'isCompleted': isCompleted,
Expand All @@ -33,7 +59,7 @@ class Task {

factory Task.fromMap(Map<String, dynamic> map) {
return Task(
id: map['id'],
id: map['id'].toString(),
title: map['title'],
description: map['description'],
createdAt: DateTime.parse(map['createdAt']),
Expand Down
29 changes: 29 additions & 0 deletions lib/models/task.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

123 changes: 123 additions & 0 deletions lib/repositories/api_task_repository.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import 'dart:convert';

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

import '../models/task.dart';
import 'task_repository.dart';

class APITaskRepository extends ChangeNotifier implements TaskRepository {
@override
Future<List<Task>> getAllTasks() async {
List<Task> tasks = [];
try {
final response = await http.get(Uri.parse('http://localhost:8080/tasks'),
headers: <String, String>{
'Content-Type': 'application/json',
});

if (response.statusCode == 200) {
Iterable jsonResponse = jsonDecode(response.body);
tasks = jsonResponse.map((task) => Task.fromJson(task)).toList();
}
return tasks;
} catch (error) {
throw Exception(error);
}
}

@override
Future<List<Task>> getCompletedTasks() async {
List<Task> tasks = [];
try {
final response = await http.get(
Uri.parse('http://localhost:8080/tasks?completed=true'),
headers: <String, String>{
'Content-Type': 'application/json',
});

if (response.statusCode == 200) {
Iterable jsonResponse = jsonDecode(response.body);
tasks = jsonResponse.map((task) => Task.fromJson(task)).toList();
}

return tasks;
} catch (error) {
throw Exception(error);
}
}

@override
Future<Task?> getTaskById(String id) async {
Task? task;
try {
final response = await http.get(
Uri.parse('http://localhost:8080/task/$id'),
headers: <String, String>{
'Content-Type': 'application/json',
});

if (response.statusCode == 200) {
Iterable jsonResponse = jsonDecode(response.body);
task = jsonResponse.map((task) => Task.fromJson(task)) as Task;
}
return task;
} catch (error) {
throw Exception(error);
}
}

@override
Future<void> addTask(Task task) async {
try {
await http.post(Uri.parse('http://localhost:8080/task'),
headers: <String, String>{
'Content-Type': 'application/json',
},
body: jsonEncode(<String, dynamic>{
'title': task.title,
'description': 'test',
'created_at': task.createdAt.toUtc().toIso8601String(),
'is_completed': task.isCompleted,
'reward_in_sats': task.rewardInSatoshis
}));
} catch (error) {
throw Exception(error);
}
notifyListeners();
}

@override
Future<void> updateTask(Task task) async {
String taskId = task.id;
try {
await http.put(Uri.parse('http://localhost:8080/task/$taskId'),
headers: <String, String>{
'Content-Type': 'application/json',
},
body: jsonEncode(<String, dynamic>{
'title': task.title,
'description': task.description,
'created_at': task.createdAt.toUtc().toIso8601String(),
'is_completed': task.isCompleted,
'reward_in_sats': task.rewardInSatoshis
}));
} catch (error) {
throw Exception(error);
}
notifyListeners();
}

@override
Future<void> deleteTask(String id) async {
try {
await http.delete(Uri.parse('http://localhost:8080/task/$id'),
headers: <String, String>{
'Content-Type': 'application/json',
});
} catch (error) {
throw Exception(error);
}
notifyListeners();
}
}
100 changes: 0 additions & 100 deletions lib/repositories/sqlite_task_repository.dart

This file was deleted.

11 changes: 5 additions & 6 deletions lib/widgets/task_add_widget.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:todo/models/task.dart';
import 'package:todo/repositories/task_repository.dart';

import '../repositories/sqlite_task_repository.dart';
import '../repositories/api_task_repository.dart';

class AddTask extends StatefulWidget {
const AddTask({
Expand All @@ -15,13 +14,13 @@ class AddTask extends StatefulWidget {

class _AddTaskState extends State<AddTask> {
final textController = TextEditingController();
late SQLiteTaskRepository taskRepository;
late APITaskRepository taskRepository;
late Future<List<Task>> taskListFuture;

@override
void initState() {
super.initState();
taskRepository = SQLiteTaskRepository();
taskRepository = APITaskRepository();
taskListFuture = taskRepository.getAllTasks();
}

Expand Down Expand Up @@ -58,12 +57,12 @@ class _AddTaskState extends State<AddTask> {
if (textController.text.isNotEmpty) {
Task task = Task(
title: textController.text,
description: '',
description: 'test',
createdAt: DateTime.now(),
isCompleted: false,
rewardInSatoshis: 0,
);
await Provider.of<SQLiteTaskRepository>(context,
await Provider.of<APITaskRepository>(context,
listen: false)
.addTask(task);
textController.clear();
Expand Down
Loading

0 comments on commit 206ba1b

Please sign in to comment.