diff --git a/assets/placeholder.webp b/assets/placeholder.webp new file mode 100644 index 0000000..bec5be2 Binary files /dev/null and b/assets/placeholder.webp differ diff --git a/lib/core/di/injection.config.dart b/lib/core/di/injection.config.dart index 2f12433..b930b7d 100644 --- a/lib/core/di/injection.config.dart +++ b/lib/core/di/injection.config.dart @@ -37,12 +37,15 @@ extension GetItInjectableX on _i174.GetIt { gh.factory<_i484.TodoRemoteDataSource>( () => _i484.TodoRemoteDataSource(gh<_i519.Client>()), ); - gh.factory<_i131.TodoRepository>( - () => _i131.TodoRepository(gh<_i484.TodoRemoteDataSource>()), - ); gh.factory<_i137.TodoLocalDataSource>( () => _i137.TodoLocalDataSource(gh<_i460.SharedPreferences>()), ); + gh.factory<_i131.TodoRepository>( + () => _i131.TodoRepository( + gh<_i484.TodoRemoteDataSource>(), + gh<_i137.TodoLocalDataSource>(), + ), + ); return this; } } diff --git a/lib/features/todo/data/datasources/todo_local_datasource.dart b/lib/features/todo/data/datasources/todo_local_datasource.dart index 78a80e3..09ea009 100644 --- a/lib/features/todo/data/datasources/todo_local_datasource.dart +++ b/lib/features/todo/data/datasources/todo_local_datasource.dart @@ -1,12 +1,26 @@ import 'package:injectable/injectable.dart'; import 'package:shared_preferences/shared_preferences.dart'; -// This class is a stub for workshop participants to implement @injectable class TodoLocalDataSource { final SharedPreferences sharedPreferences; - // ignore: unused_field - final String _todoKey = 'todos'; + final String _todoFavouriteKey = 'favourite_todos'; TodoLocalDataSource(this.sharedPreferences); + + Future> getFavouriteTodos() async { + try { + return sharedPreferences.getStringList(_todoFavouriteKey) ?? []; + } catch (e) { + return []; + } + } + + Future setFavouriteTodos(List todoIds) async { + try { + await sharedPreferences.setStringList(_todoFavouriteKey, todoIds); + } catch (e) { + return; + } + } } diff --git a/lib/features/todo/data/datasources/todo_remote_datasource.dart b/lib/features/todo/data/datasources/todo_remote_datasource.dart index 8c3ef0b..62333f0 100644 --- a/lib/features/todo/data/datasources/todo_remote_datasource.dart +++ b/lib/features/todo/data/datasources/todo_remote_datasource.dart @@ -10,8 +10,7 @@ import '../models/todo_dto.dart'; @injectable class TodoRemoteDataSource { final http.Client _client; - // TODO: Replace this with the URL we provide you - final String baseUrl = 'https://6825aa0f0f0188d7e72ddd9a.mockapi.io/api/v1'; + final String baseUrl = 'https://68346e5b464b49963602ccb5.mockapi.io'; TodoRemoteDataSource(this._client); @@ -32,9 +31,14 @@ class TodoRemoteDataSource { } } - Future addTodo(String title) async { + Future addTodo(String title, String? description, String? imageUrl) async { try { - final newTodo = {'title': title, 'createdAtSeconds': DateTime.now().millisecondsSinceEpoch ~/ 1000}; + final newTodo = { + 'title': title, + 'description': description, + 'imageUrl': imageUrl, + 'createdAtSeconds': DateTime.now().millisecondsSinceEpoch ~/ 1000, + }; log('Sending todo: ${json.encode(newTodo)}'); @@ -61,6 +65,51 @@ class TodoRemoteDataSource { } } + Future deleteTodo(String id) async { + try { + final response = await _client.delete(Uri.parse('$baseUrl/todo/$id')); + + log('Response status: ${response.statusCode}'); + log('Response body: ${response.body}'); + + if (response.statusCode != 200) { + throw Exception('Failed to delete todo: ${response.statusCode}'); + } + } catch (e) { + log('Error deleting todo: $e'); + throw Exception('Failed to delete todo: $e'); + } + } + + Future updateTodoStatus(String id, bool isDone) async { + try { + final newTodo = {'isDone': isDone}; + + log('Updating todo status: ${json.encode(newTodo)}'); + + final response = await _client.patch( + Uri.parse('$baseUrl/todo/$id'), + headers: {'Content-Type': 'application/json'}, + body: json.encode(newTodo), + ); + + log('Response status: ${response.statusCode}'); + log('Response body: ${response.body}'); + + if (response.statusCode == 201 || response.statusCode == 200) { + final Map responseData = json.decode(response.body); + + // If the API response is not in the expected format, transform it + return TodoDTO.fromJson(responseData); + } else { + throw Exception('Failed to update todo: ${response.statusCode}'); + } + } catch (e) { + log('Error updating todo: $e'); + throw Exception('Failed to update todo: $e'); + } + } + // For local client-side ID generation String generateId() { return const Uuid().v4(); diff --git a/lib/features/todo/data/models/todo_dto.dart b/lib/features/todo/data/models/todo_dto.dart index 8d9d649..4839b0a 100644 --- a/lib/features/todo/data/models/todo_dto.dart +++ b/lib/features/todo/data/models/todo_dto.dart @@ -10,6 +10,9 @@ class TodoDTO with _$TodoDTO { const factory TodoDTO({ required String id, required String title, + String? description, + String? imageUrl, + bool? isDone, int? createdAtSeconds, }) = _TodoDTO; diff --git a/lib/features/todo/data/models/todo_dto.freezed.dart b/lib/features/todo/data/models/todo_dto.freezed.dart index 752b03e..6aede62 100644 --- a/lib/features/todo/data/models/todo_dto.freezed.dart +++ b/lib/features/todo/data/models/todo_dto.freezed.dart @@ -23,6 +23,9 @@ TodoDTO _$TodoDTOFromJson(Map json) { mixin _$TodoDTO { String get id => throw _privateConstructorUsedError; String get title => throw _privateConstructorUsedError; + String? get description => throw _privateConstructorUsedError; + String? get imageUrl => throw _privateConstructorUsedError; + bool? get isDone => throw _privateConstructorUsedError; int? get createdAtSeconds => throw _privateConstructorUsedError; /// Serializes this TodoDTO to a JSON map. @@ -39,7 +42,14 @@ abstract class $TodoDTOCopyWith<$Res> { factory $TodoDTOCopyWith(TodoDTO value, $Res Function(TodoDTO) then) = _$TodoDTOCopyWithImpl<$Res, TodoDTO>; @useResult - $Res call({String id, String title, int? createdAtSeconds}); + $Res call({ + String id, + String title, + String? description, + String? imageUrl, + bool? isDone, + int? createdAtSeconds, + }); } /// @nodoc @@ -59,6 +69,9 @@ class _$TodoDTOCopyWithImpl<$Res, $Val extends TodoDTO> $Res call({ Object? id = null, Object? title = null, + Object? description = freezed, + Object? imageUrl = freezed, + Object? isDone = freezed, Object? createdAtSeconds = freezed, }) { return _then( @@ -73,6 +86,21 @@ class _$TodoDTOCopyWithImpl<$Res, $Val extends TodoDTO> ? _value.title : title // ignore: cast_nullable_to_non_nullable as String, + description: + freezed == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String?, + imageUrl: + freezed == imageUrl + ? _value.imageUrl + : imageUrl // ignore: cast_nullable_to_non_nullable + as String?, + isDone: + freezed == isDone + ? _value.isDone + : isDone // ignore: cast_nullable_to_non_nullable + as bool?, createdAtSeconds: freezed == createdAtSeconds ? _value.createdAtSeconds @@ -92,7 +120,14 @@ abstract class _$$TodoDTOImplCopyWith<$Res> implements $TodoDTOCopyWith<$Res> { ) = __$$TodoDTOImplCopyWithImpl<$Res>; @override @useResult - $Res call({String id, String title, int? createdAtSeconds}); + $Res call({ + String id, + String title, + String? description, + String? imageUrl, + bool? isDone, + int? createdAtSeconds, + }); } /// @nodoc @@ -111,6 +146,9 @@ class __$$TodoDTOImplCopyWithImpl<$Res> $Res call({ Object? id = null, Object? title = null, + Object? description = freezed, + Object? imageUrl = freezed, + Object? isDone = freezed, Object? createdAtSeconds = freezed, }) { return _then( @@ -125,6 +163,21 @@ class __$$TodoDTOImplCopyWithImpl<$Res> ? _value.title : title // ignore: cast_nullable_to_non_nullable as String, + description: + freezed == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String?, + imageUrl: + freezed == imageUrl + ? _value.imageUrl + : imageUrl // ignore: cast_nullable_to_non_nullable + as String?, + isDone: + freezed == isDone + ? _value.isDone + : isDone // ignore: cast_nullable_to_non_nullable + as bool?, createdAtSeconds: freezed == createdAtSeconds ? _value.createdAtSeconds @@ -141,6 +194,9 @@ class _$TodoDTOImpl extends _TodoDTO { const _$TodoDTOImpl({ required this.id, required this.title, + this.description, + this.imageUrl, + this.isDone, this.createdAtSeconds, }) : super._(); @@ -152,11 +208,17 @@ class _$TodoDTOImpl extends _TodoDTO { @override final String title; @override + final String? description; + @override + final String? imageUrl; + @override + final bool? isDone; + @override final int? createdAtSeconds; @override String toString() { - return 'TodoDTO(id: $id, title: $title, createdAtSeconds: $createdAtSeconds)'; + return 'TodoDTO(id: $id, title: $title, description: $description, imageUrl: $imageUrl, isDone: $isDone, createdAtSeconds: $createdAtSeconds)'; } @override @@ -166,13 +228,26 @@ class _$TodoDTOImpl extends _TodoDTO { other is _$TodoDTOImpl && (identical(other.id, id) || other.id == id) && (identical(other.title, title) || other.title == title) && + (identical(other.description, description) || + other.description == description) && + (identical(other.imageUrl, imageUrl) || + other.imageUrl == imageUrl) && + (identical(other.isDone, isDone) || other.isDone == isDone) && (identical(other.createdAtSeconds, createdAtSeconds) || other.createdAtSeconds == createdAtSeconds)); } @JsonKey(includeFromJson: false, includeToJson: false) @override - int get hashCode => Object.hash(runtimeType, id, title, createdAtSeconds); + int get hashCode => Object.hash( + runtimeType, + id, + title, + description, + imageUrl, + isDone, + createdAtSeconds, + ); /// Create a copy of TodoDTO /// with the given fields replaced by the non-null parameter values. @@ -192,6 +267,9 @@ abstract class _TodoDTO extends TodoDTO { const factory _TodoDTO({ required final String id, required final String title, + final String? description, + final String? imageUrl, + final bool? isDone, final int? createdAtSeconds, }) = _$TodoDTOImpl; const _TodoDTO._() : super._(); @@ -203,6 +281,12 @@ abstract class _TodoDTO extends TodoDTO { @override String get title; @override + String? get description; + @override + String? get imageUrl; + @override + bool? get isDone; + @override int? get createdAtSeconds; /// Create a copy of TodoDTO diff --git a/lib/features/todo/data/models/todo_dto.g.dart b/lib/features/todo/data/models/todo_dto.g.dart index bada3c6..d724020 100644 --- a/lib/features/todo/data/models/todo_dto.g.dart +++ b/lib/features/todo/data/models/todo_dto.g.dart @@ -10,6 +10,9 @@ _$TodoDTOImpl _$$TodoDTOImplFromJson(Map json) => _$TodoDTOImpl( id: json['id'] as String, title: json['title'] as String, + description: json['description'] as String?, + imageUrl: json['imageUrl'] as String?, + isDone: json['isDone'] as bool?, createdAtSeconds: (json['createdAtSeconds'] as num?)?.toInt(), ); @@ -17,5 +20,8 @@ Map _$$TodoDTOImplToJson(_$TodoDTOImpl instance) => { 'id': instance.id, 'title': instance.title, + 'description': instance.description, + 'imageUrl': instance.imageUrl, + 'isDone': instance.isDone, 'createdAtSeconds': instance.createdAtSeconds, }; diff --git a/lib/features/todo/data/repositories/todo_repository.dart b/lib/features/todo/data/repositories/todo_repository.dart index 49e63b0..96a7e01 100644 --- a/lib/features/todo/data/repositories/todo_repository.dart +++ b/lib/features/todo/data/repositories/todo_repository.dart @@ -4,23 +4,26 @@ import 'package:injectable/injectable.dart'; import 'package:uuid/uuid.dart'; import '../../domain/models/todo_model.dart'; +import '../datasources/todo_local_datasource.dart'; import '../datasources/todo_remote_datasource.dart'; import '../models/todo_dto.dart'; @injectable class TodoRepository { final TodoRemoteDataSource remoteDataSource; + final TodoLocalDataSource localDataSource; - TodoRepository(this.remoteDataSource); + TodoRepository(this.remoteDataSource, this.localDataSource); // Get todos from remote data source only Future> getTodos() async { try { // Get todos from the API final remoteDtos = await remoteDataSource.getTodos(); + final favouriteIds = await localDataSource.getFavouriteTodos(); // Map DTOs to domain models - final todos = remoteDtos.map(_mapDtoToModel).toList(); + final todos = remoteDtos.map((dto) => _mapDtoToModel(dto, favouriteIds)).toList(); // Sort todos by creation date (newest first) todos.sort((a, b) => b.effectiveCreatedAt.compareTo(a.effectiveCreatedAt)); @@ -34,27 +37,78 @@ class TodoRepository { } // Add a new todo remotely - Future addTodo(String title) async { + Future addTodo(String title, String? description, String? imageUrl) async { try { // Add todo remotely - await remoteDataSource.addTodo(title); + await remoteDataSource.addTodo(title, description, imageUrl); } catch (e) { log('Error adding remote todo: $e'); } } + Future deleteTodo(String id) async { + try { + // Delete todo remotely + await remoteDataSource.deleteTodo(id); + } catch (e) { + log('Error deleting remote todo: $e'); + } + } + + Future updateTodoStatus(String id, bool isDone) async { + try { + // Update todo status remotely + final favouriteIds = await localDataSource.getFavouriteTodos(); + + return _mapDtoToModel(await remoteDataSource.updateTodoStatus(id, isDone), favouriteIds); + } catch (e) { + log('Error updating remote todo status: $e'); + return null; + } + } + + Future toggleTodoFavourite(String id) async { + try { + final favouriteIds = await localDataSource.getFavouriteTodos(); + + final isFavourite = favouriteIds.contains(id); + + if (isFavourite) { + favouriteIds.remove(id); + } else { + favouriteIds.add(id); + } + + await localDataSource.setFavouriteTodos(favouriteIds); + + return !isFavourite; + } catch (e) { + log('Error toggling todo favourite: $e'); + return null; + } + } + // Helper method to map DTOs to domain models - TodoModel _mapDtoToModel(TodoDTO dto) { + TodoModel _mapDtoToModel(TodoDTO dto, List favouriteIds) { try { DateTime? createdAt; if (dto.createdAtSeconds != null) { createdAt = DateTime.fromMillisecondsSinceEpoch(dto.createdAtSeconds! * 1000); } + final isFavourite = favouriteIds.contains(dto.id); - return TodoModel(id: dto.id, title: dto.title, createdAt: createdAt); + return TodoModel( + id: dto.id, + title: dto.title, + description: dto.description, + imageUrl: dto.imageUrl, + isDone: dto.isDone, + isFavourite: isFavourite, + createdAt: createdAt, + ); } catch (e) { log('Error mapping DTO to model: $e'); - return TodoModel(id: const Uuid().v4(), title: 'Unknown title', createdAt: DateTime.now()); + return TodoModel(id: const Uuid().v4(), title: 'Unknown title', isFavourite: false, createdAt: DateTime.now()); } } } diff --git a/lib/features/todo/domain/models/todo_model.dart b/lib/features/todo/domain/models/todo_model.dart index 606a711..7c72c1f 100644 --- a/lib/features/todo/domain/models/todo_model.dart +++ b/lib/features/todo/domain/models/todo_model.dart @@ -2,14 +2,22 @@ import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:intl/intl.dart'; part 'todo_model.freezed.dart'; + part 'todo_model.g.dart'; @freezed class TodoModel with _$TodoModel { const TodoModel._(); - const factory TodoModel({required String id, required String title, DateTime? createdAt}) = - _TodoModel; + const factory TodoModel({ + required String id, + required String title, + required bool isFavourite, + String? description, + String? imageUrl, + bool? isDone, + DateTime? createdAt, + }) = _TodoModel; DateTime get effectiveCreatedAt => createdAt ?? DateTime.now(); diff --git a/lib/features/todo/domain/models/todo_model.freezed.dart b/lib/features/todo/domain/models/todo_model.freezed.dart index 6052b7a..c6c2ae1 100644 --- a/lib/features/todo/domain/models/todo_model.freezed.dart +++ b/lib/features/todo/domain/models/todo_model.freezed.dart @@ -23,6 +23,10 @@ TodoModel _$TodoModelFromJson(Map json) { mixin _$TodoModel { String get id => throw _privateConstructorUsedError; String get title => throw _privateConstructorUsedError; + bool get isFavourite => throw _privateConstructorUsedError; + String? get description => throw _privateConstructorUsedError; + String? get imageUrl => throw _privateConstructorUsedError; + bool? get isDone => throw _privateConstructorUsedError; DateTime? get createdAt => throw _privateConstructorUsedError; /// Serializes this TodoModel to a JSON map. @@ -40,7 +44,15 @@ abstract class $TodoModelCopyWith<$Res> { factory $TodoModelCopyWith(TodoModel value, $Res Function(TodoModel) then) = _$TodoModelCopyWithImpl<$Res, TodoModel>; @useResult - $Res call({String id, String title, DateTime? createdAt}); + $Res call({ + String id, + String title, + bool isFavourite, + String? description, + String? imageUrl, + bool? isDone, + DateTime? createdAt, + }); } /// @nodoc @@ -60,6 +72,10 @@ class _$TodoModelCopyWithImpl<$Res, $Val extends TodoModel> $Res call({ Object? id = null, Object? title = null, + Object? isFavourite = null, + Object? description = freezed, + Object? imageUrl = freezed, + Object? isDone = freezed, Object? createdAt = freezed, }) { return _then( @@ -74,6 +90,26 @@ class _$TodoModelCopyWithImpl<$Res, $Val extends TodoModel> ? _value.title : title // ignore: cast_nullable_to_non_nullable as String, + isFavourite: + null == isFavourite + ? _value.isFavourite + : isFavourite // ignore: cast_nullable_to_non_nullable + as bool, + description: + freezed == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String?, + imageUrl: + freezed == imageUrl + ? _value.imageUrl + : imageUrl // ignore: cast_nullable_to_non_nullable + as String?, + isDone: + freezed == isDone + ? _value.isDone + : isDone // ignore: cast_nullable_to_non_nullable + as bool?, createdAt: freezed == createdAt ? _value.createdAt @@ -94,7 +130,15 @@ abstract class _$$TodoModelImplCopyWith<$Res> ) = __$$TodoModelImplCopyWithImpl<$Res>; @override @useResult - $Res call({String id, String title, DateTime? createdAt}); + $Res call({ + String id, + String title, + bool isFavourite, + String? description, + String? imageUrl, + bool? isDone, + DateTime? createdAt, + }); } /// @nodoc @@ -113,6 +157,10 @@ class __$$TodoModelImplCopyWithImpl<$Res> $Res call({ Object? id = null, Object? title = null, + Object? isFavourite = null, + Object? description = freezed, + Object? imageUrl = freezed, + Object? isDone = freezed, Object? createdAt = freezed, }) { return _then( @@ -127,6 +175,26 @@ class __$$TodoModelImplCopyWithImpl<$Res> ? _value.title : title // ignore: cast_nullable_to_non_nullable as String, + isFavourite: + null == isFavourite + ? _value.isFavourite + : isFavourite // ignore: cast_nullable_to_non_nullable + as bool, + description: + freezed == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String?, + imageUrl: + freezed == imageUrl + ? _value.imageUrl + : imageUrl // ignore: cast_nullable_to_non_nullable + as String?, + isDone: + freezed == isDone + ? _value.isDone + : isDone // ignore: cast_nullable_to_non_nullable + as bool?, createdAt: freezed == createdAt ? _value.createdAt @@ -140,8 +208,15 @@ class __$$TodoModelImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() class _$TodoModelImpl extends _TodoModel { - const _$TodoModelImpl({required this.id, required this.title, this.createdAt}) - : super._(); + const _$TodoModelImpl({ + required this.id, + required this.title, + required this.isFavourite, + this.description, + this.imageUrl, + this.isDone, + this.createdAt, + }) : super._(); factory _$TodoModelImpl.fromJson(Map json) => _$$TodoModelImplFromJson(json); @@ -151,11 +226,19 @@ class _$TodoModelImpl extends _TodoModel { @override final String title; @override + final bool isFavourite; + @override + final String? description; + @override + final String? imageUrl; + @override + final bool? isDone; + @override final DateTime? createdAt; @override String toString() { - return 'TodoModel(id: $id, title: $title, createdAt: $createdAt)'; + return 'TodoModel(id: $id, title: $title, isFavourite: $isFavourite, description: $description, imageUrl: $imageUrl, isDone: $isDone, createdAt: $createdAt)'; } @override @@ -165,13 +248,29 @@ class _$TodoModelImpl extends _TodoModel { other is _$TodoModelImpl && (identical(other.id, id) || other.id == id) && (identical(other.title, title) || other.title == title) && + (identical(other.isFavourite, isFavourite) || + other.isFavourite == isFavourite) && + (identical(other.description, description) || + other.description == description) && + (identical(other.imageUrl, imageUrl) || + other.imageUrl == imageUrl) && + (identical(other.isDone, isDone) || other.isDone == isDone) && (identical(other.createdAt, createdAt) || other.createdAt == createdAt)); } @JsonKey(includeFromJson: false, includeToJson: false) @override - int get hashCode => Object.hash(runtimeType, id, title, createdAt); + int get hashCode => Object.hash( + runtimeType, + id, + title, + isFavourite, + description, + imageUrl, + isDone, + createdAt, + ); /// Create a copy of TodoModel /// with the given fields replaced by the non-null parameter values. @@ -191,6 +290,10 @@ abstract class _TodoModel extends TodoModel { const factory _TodoModel({ required final String id, required final String title, + required final bool isFavourite, + final String? description, + final String? imageUrl, + final bool? isDone, final DateTime? createdAt, }) = _$TodoModelImpl; const _TodoModel._() : super._(); @@ -203,6 +306,14 @@ abstract class _TodoModel extends TodoModel { @override String get title; @override + bool get isFavourite; + @override + String? get description; + @override + String? get imageUrl; + @override + bool? get isDone; + @override DateTime? get createdAt; /// Create a copy of TodoModel diff --git a/lib/features/todo/domain/models/todo_model.g.dart b/lib/features/todo/domain/models/todo_model.g.dart index 6512f96..64ca82e 100644 --- a/lib/features/todo/domain/models/todo_model.g.dart +++ b/lib/features/todo/domain/models/todo_model.g.dart @@ -10,6 +10,10 @@ _$TodoModelImpl _$$TodoModelImplFromJson(Map json) => _$TodoModelImpl( id: json['id'] as String, title: json['title'] as String, + isFavourite: json['isFavourite'] as bool, + description: json['description'] as String?, + imageUrl: json['imageUrl'] as String?, + isDone: json['isDone'] as bool?, createdAt: json['createdAt'] == null ? null @@ -20,5 +24,9 @@ Map _$$TodoModelImplToJson(_$TodoModelImpl instance) => { 'id': instance.id, 'title': instance.title, + 'isFavourite': instance.isFavourite, + 'description': instance.description, + 'imageUrl': instance.imageUrl, + 'isDone': instance.isDone, 'createdAt': instance.createdAt?.toIso8601String(), }; diff --git a/lib/features/todo/presentation/cubits/todo_cubit.dart b/lib/features/todo/presentation/cubits/todo_cubit.dart index f1805f4..069cecc 100644 --- a/lib/features/todo/presentation/cubits/todo_cubit.dart +++ b/lib/features/todo/presentation/cubits/todo_cubit.dart @@ -9,6 +9,8 @@ part 'todo_state.dart'; class TodoCubit extends Cubit { final TodoRepository _repository; + TodosLoaded get loaded => state as TodosLoaded; + TodoCubit(this._repository) : super(TodosLoading()); Future loadTodos() async { @@ -21,10 +23,48 @@ class TodoCubit extends Cubit { } } - Future addTodo(String title) async { + Future addTodo(String title, String? description, String? imageUrl) async { + try { + emit(TodosLoading()); + await _repository.addTodo(title, description, imageUrl); + await loadTodos(); + } catch (e) { + emit(TodosError(message: e.toString())); + } + } + + Future updateTodoStatus(String id, bool isDone) async { + try { + final updatedTodo = await _repository.updateTodoStatus(id, isDone); + + if (updatedTodo != null) { + emit(TodosLoaded(todos: loaded.todos.map((todo) => todo.id == id ? updatedTodo : todo).toList())); + } + } catch (e) { + emit(TodosError(message: e.toString())); + } + } + + Future toggleTodoFavourite(String id) async { + try { + TodoModel? currentTodo = loaded.todos.firstWhere((todo) => todo.id == id); + + final updatedFavorite = await _repository.toggleTodoFavourite(id); + + if (updatedFavorite == null) return; + + TodoModel updatedTodo = currentTodo.copyWith(isFavourite: updatedFavorite); + + emit(TodosLoaded(todos: loaded.todos.map((todo) => todo.id == id ? updatedTodo : todo).toList())); + } catch (e) { + emit(TodosError(message: e.toString())); + } + } + + Future deleteTodo(String id) async { try { emit(TodosLoading()); - await _repository.addTodo(title); + await _repository.deleteTodo(id); await loadTodos(); } catch (e) { emit(TodosError(message: e.toString())); diff --git a/lib/features/todo/presentation/screens/todo_detail_screen.dart b/lib/features/todo/presentation/screens/todo_detail_screen.dart new file mode 100644 index 0000000..8d24ee6 --- /dev/null +++ b/lib/features/todo/presentation/screens/todo_detail_screen.dart @@ -0,0 +1,92 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_todo_workshop/features/todo/domain/models/todo_model.dart'; + +import '../cubits/todo_cubit.dart'; + +class TodoDetailScreen extends StatelessWidget { + final String todoId; + + const TodoDetailScreen({super.key, required this.todoId}); + + @override + Widget build(BuildContext context) { + final todoCubit = context.read(); + + return BlocBuilder( + builder: (context, state) { + TodoModel? todo; + try { + todo = state is TodosLoaded ? state.todos.firstWhere((todo) => todo.id == todoId) : null; + } catch (e) { + todo = null; + } + + if (todo != null) { + return Scaffold( + appBar: AppBar( + title: Text("Detail"), + actions: [ + IconButton( + icon: Icon( + todo.isFavourite ? Icons.star : Icons.star_border, + color: todo.isFavourite ? Colors.amber : null, + ), + onPressed: () => todoCubit.toggleTodoFavourite(todo!.id), + tooltip: 'Favorite', + ), + ], + ), + body: SafeArea( + child: Column( + children: [ + SizedBox( + height: 200, + width: double.infinity, + child: + todo.imageUrl != null && todo.imageUrl!.isNotEmpty + ? Image.network(todo.imageUrl!, fit: BoxFit.cover) + : Image.asset('assets/placeholder.webp'), + ), + Expanded( + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: 8, + children: [ + Text(todo.title, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold)), + todo.description != null && todo.description!.isNotEmpty + ? Text(todo.description!, style: const TextStyle(fontSize: 14)) + : const SizedBox(), + Expanded(child: const SizedBox()), + Text( + todo.formattedDate, + style: TextStyle(fontSize: 12, color: Colors.grey[600], fontStyle: FontStyle.italic), + ), + ElevatedButton( + onPressed: () { + todoCubit.deleteTodo(todo!.id); + Navigator.pop(context); + }, + style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 16)), + child: const Text('Delete', style: TextStyle(color: Colors.redAccent)), + ), + ], + ), + ), + ), + ], + ), + ), + ); + } else { + return Scaffold( + appBar: AppBar(title: const Text('Todo Detail')), + body: const Center(child: Text('Todo not found')), + ); + } + }, + ); + } +} diff --git a/lib/features/todo/presentation/screens/todo_form_screen.dart b/lib/features/todo/presentation/screens/todo_form_screen.dart index cf54e93..cd4beaa 100644 --- a/lib/features/todo/presentation/screens/todo_form_screen.dart +++ b/lib/features/todo/presentation/screens/todo_form_screen.dart @@ -13,6 +13,8 @@ class TodoFormScreen extends StatefulWidget { class _TodoFormScreenState extends State { final _formKey = GlobalKey(); final _titleController = TextEditingController(); + final _descriptionController = TextEditingController(); + final _imageUrlController = TextEditingController(); @override void dispose() { @@ -22,7 +24,7 @@ class _TodoFormScreenState extends State { void _submitForm() { if (_formKey.currentState?.validate() ?? false) { - context.read().addTodo(_titleController.text); + context.read().addTodo(_titleController.text, _descriptionController.text, _imageUrlController.text); Navigator.pop(context); } } @@ -31,31 +33,44 @@ class _TodoFormScreenState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Add Todo')), - body: Padding( - padding: const EdgeInsets.all(16.0), - child: Form( - key: _formKey, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - const SizedBox(height: 16), - TextFormField( - controller: _titleController, - decoration: const InputDecoration(labelText: 'Title', border: OutlineInputBorder()), - validator: (value) { - if (value == null || value.isEmpty) { - return 'Please enter a title'; - } - return null; - }, - ), - const SizedBox(height: 24), - ElevatedButton( - onPressed: _submitForm, - style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 16)), - child: const Text('Add Todo'), - ), - ], + body: SafeArea( + child: Padding( + padding: const EdgeInsets.only(left: 16, right: 16, top: 16), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: 16, + children: [ + TextFormField( + controller: _titleController, + decoration: const InputDecoration(labelText: 'Title', border: OutlineInputBorder()), + validator: (value) { + if (value == null || value.isEmpty) { + return 'Please enter a title'; + } + return null; + }, + ), + TextFormField( + controller: _descriptionController, + decoration: const InputDecoration(labelText: 'Description', border: OutlineInputBorder()), + keyboardType: TextInputType.multiline, + minLines: 2, + maxLines: 10, + ), + TextFormField( + controller: _imageUrlController, + decoration: const InputDecoration(labelText: 'Image url', border: OutlineInputBorder()), + ), + Expanded(child: const SizedBox()), + ElevatedButton( + onPressed: _submitForm, + style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 16)), + child: const Text('Add Todo'), + ), + ], + ), ), ), ), diff --git a/lib/features/todo/presentation/screens/todo_list_screen.dart b/lib/features/todo/presentation/screens/todo_list_screen.dart index a366ba1..ccd2bb7 100644 --- a/lib/features/todo/presentation/screens/todo_list_screen.dart +++ b/lib/features/todo/presentation/screens/todo_list_screen.dart @@ -3,6 +3,7 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import '../cubits/todo_cubit.dart'; import '../widgets/todo_item.dart'; +import 'todo_detail_screen.dart'; import 'todo_form_screen.dart'; class TodoListScreen extends StatelessWidget { @@ -35,7 +36,19 @@ class TodoListScreen extends StatelessWidget { return ListView.builder( itemCount: todos.length, itemBuilder: (context, index) { - return TodoItem(todo: todos[index]); + return GestureDetector( + child: TodoItem(todo: todos[index]), + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: + (context) => + BlocProvider.value(value: todoCubit, child: TodoDetailScreen(todoId: todos[index].id)), + ), + ); + }, + ); }, ); } else if (state is TodosError) { diff --git a/lib/features/todo/presentation/widgets/todo_item.dart b/lib/features/todo/presentation/widgets/todo_item.dart index 0930dea..bfdf70c 100644 --- a/lib/features/todo/presentation/widgets/todo_item.dart +++ b/lib/features/todo/presentation/widgets/todo_item.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; import '../../domain/models/todo_model.dart'; +import '../cubits/todo_cubit.dart'; class TodoItem extends StatelessWidget { final TodoModel todo; @@ -9,19 +11,55 @@ class TodoItem extends StatelessWidget { @override Widget build(BuildContext context) { + final todoCubit = context.read(); + return Card( elevation: 2, margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), child: Padding( padding: const EdgeInsets.all(12.0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, + child: Row( + spacing: 8, children: [ - Text(todo.title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), - const SizedBox(height: 4), - Text( - todo.formattedDate, - style: TextStyle(fontSize: 12, color: Colors.grey[600], fontStyle: FontStyle.italic), + SizedBox( + height: 50, + width: 50, + child: + todo.imageUrl != null && todo.imageUrl!.isNotEmpty + ? Image.network(todo.imageUrl!, fit: BoxFit.cover) + : Image.asset('assets/placeholder.webp'), + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + todo.title, + style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + overflow: TextOverflow.ellipsis, + ), + todo.description != null && todo.description!.isNotEmpty + ? Text( + todo.description!, + style: const TextStyle(fontSize: 14), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ) + : const SizedBox(), + + const SizedBox(height: 4), + Text( + todo.formattedDate, + style: TextStyle(fontSize: 12, color: Colors.grey[600], fontStyle: FontStyle.italic), + ), + ], + ), + ), + Checkbox( + value: todo.isDone, + onChanged: (value) { + todoCubit.updateTodoStatus(todo.id, value ?? false); + }, ), ], ), diff --git a/pubspec.yaml b/pubspec.yaml index dcd7080..83fe57a 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -33,3 +33,5 @@ dev_dependencies: freezed: ^2.4.7 flutter: uses-material-design: true + assets: + - assets/