This is a perfectly functioning animated code i flutter using stack and tween. Rewrite it using animatedlist : import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
class _SignUpPageState extends State {
final emailController = TextEditingController();
final passwordController = TextEditingController();
final confirmPasswordController = TextEditingController();
final phoneController = TextEditingController();
final nomeController = TextEditingController();
Future signUp() async {
if (passwordController.text != confirmPasswordController.text) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('As senhas não coincidem.')));
return;
}
Assistant
final Map<String, dynamic> body = {
'celular': '21900000000',
'email': emailController.text,
'nome': nomeController.text,
'senha': passwordController.text,
};
if (phoneController.text.isNotEmpty) {
body['celular'] = phoneController.text;
}
final response = await http.post(
Uri.parse('https://barra.cos.ufrj.br:443/rest/rpc/registra_usuario'),
headers: {'Content-Type': 'application/json'},
body: json.encode(body),
);
if (response.statusCode == 200) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Usuário cadastrado com sucesso!')));
final loginResponse = await http.post(
Uri.parse('https://barra.cos.ufrj.br:443/rest/rpc/fazer_login'),
headers: {
'accept': 'application/json',
'Content-Type': 'application/json',
},
body: json.encode({
'email': emailController.text,
'senha': passwordController.text,
}),
);
if (loginResponse.statusCode == 200) {
final loginData = json.decode(loginResponse.body);
final String token = loginData['token'];
await criarTarefas(token, emailController.text);
Navigator.pop(context);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Erro ao obter token de login.')));
}
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Erro ao cadastrar.')));
}
}
Future criarTarefas(String token, String email) async {
final url = Uri.https('barra.cos.ufrj.br:443', '/rest/tarefas');
final headers = {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
};
final body = json.encode({
'email': email,
'valor': [],
});
// Move the task to the position after the last incomplete task
Map<String, dynamic> completedTask = tasks.removeAt(index);
int newIndex = tasks.length; // By default, insert at the end
for (int i = 0; i < tasks.length; i++) {
if (tasks[i]['concluida'] == true) {
newIndex = i;
break;
}
}
tasks.insert(newIndex, completedTask);
// Reset isAnimating after the animation duration
Future.delayed(Duration(milliseconds: 500), () {
setState(() {
completedTask['isAnimating'] = false;
});
});
} else {
// Un-completing the task
tasks[index]['concluida'] = false;
// Move the task to the end of incomplete tasks
Map<String, dynamic> uncompletedTask = tasks.removeAt(index);
int lastIncompleteIndex = -1;
for (int i = 0; i < tasks.length; i++) {
if (tasks[i]['concluida'] == false) {
lastIncompleteIndex = i;
}
}
tasks.insert(lastIncompleteIndex + 1, uncompletedTask);
}
});
updateTasksOnServer();
Certainly! Below is the rewritten code for your TaskListPage, replacing the Stack and Tween animations with an AnimatedList. The AnimatedList widget handles insertions and deletions with built-in animations, making it suitable for your use case.
AnimatedList Initialization: Replaced the Stack with an AnimatedList. The AnimatedList widget is initialized with the tasks.length and a GlobalKey to manage its state.
Item Builder: The itemBuilder of AnimatedList builds each task item using a SizeTransition for a smooth expanding/collapsing animation.
Adding Tasks: In the addTask method, after inserting the new task into the list, we call _listKey.currentState!.insertItem(0); to animate the insertion at the top of the list.
Deleting Tasks: The _deleteTaskWithUndo method removes the task from the list and calls _listKey.currentState!.removeItem(index, builder); to animate the removal. It also shows a SnackBar with an "Undo" option to restore the deleted task.
Toggling Completion: In _toggleCompletion, the task is removed from its current position and re-inserted at the new position based on its completion status. This is done by removing the item and calling removeItem for the animation, then inserting it at the new index and calling insertItem.
Build Method: The build method now checks if tasks have been loaded (_tasksLoaded). If not, it displays a CircularProgressIndicator. Once loaded, it builds the AnimatedList.
Task Tile: The buildTaskTile method creates the ListTile for each task, including the checkbox and delete button.
Note: The AnimatedList widget doesn't support moving items directly with animations. To animate the movement of an item (like moving a task from incomplete to complete), we remove it from its current position and insert it at the new position, triggering the appropriate animations.
Additional Considerations:
Index Management: Care was taken to manage indices correctly, especially when items are removed or inserted, as the list's length and item positions change.
Asynchronous Operations: Network calls remain asynchronous, and the UI updates are triggered using setState to reflect changes.
User Feedback: SnackBar widgets provide feedback to the user when tasks are deleted, allowing them to undo actions.
This implementation using AnimatedList should provide a smooth and efficient user experience while managing tasks in your app.