I need help with my flutter code. It can't create lists. I'm receiving error 400: import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class _SignUpPageState extends State {
final emailController = TextEditingController();
final nomeController = TextEditingController();
final passwordController = TextEditingController();
final confirmPasswordController = TextEditingController();
final phoneController = TextEditingController();
Future signUp() async {
if (passwordController.text != confirmPasswordController.text) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('As senhas não coincidem.')));
return;
}
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!')));
Navigator.pop(context);
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Erro ao cadastrar.')));
}
try {
final response = await http.delete(url, headers: headers);
if (response.statusCode == 204) {
setState(() {
taskLists.removeWhere((taskList) => taskList['id'].toString() == taskListId);
});
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content:
Text('Erro ao deletar lista de tarefas: ${response.statusCode}')),
);
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Erro: ${e.toString()}')),
);
}
}
Future _createNewTaskList(String title) async {
if (title.trim().isEmpty) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('O título não pode ser vazio.')));
return;
}
final url = Uri.parse('https://barra.cos.ufrj.br/rest/tarefasv2');
final headers = {
'Authorization': 'Bearer ${widget.token}',
'Content-Type': 'application/json',
};
final body = json.encode({
'email': widget.email,
'titulo': title,
'valor': [],
'atributos': {},
});
try {
final response = await http.post(url, headers: headers, body: body);
if (response.statusCode == 201) {
_fetchTaskLists();
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Lista criada com sucesso!')));
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content:
Text('Erro ao criar lista de tarefas: ${response.statusCode}')),
);
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Erro: ${e.toString()}')),
);
}
// ---------------------------------
// TaskListPage
// ---------------------------------
class TaskListPage extends StatefulWidget {
final String token;
final String email;
final String taskListId;
final String titulo;
// ---------------------------------
// ChatPage
// ---------------------------------
class ChatPage extends StatefulWidget {
final String token;
final String email;
final String? conversaId;
Future _enviarMensagem(String texto) async {
if (texto.trim().isEmpty) return;
if (conversaId == null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Conversa não iniciada.')),
);
return;
}
setState(() {
messages.add({'papel': 'usuario', 'conteudo': texto.trim()});
isLoading = true;
});
_scrollToBottom();
textController.clear();
final url = Uri.parse('https://barra.cos.ufrj.br/rest/rpc/envia_resposta');
final headers = {
'Authorization': 'Bearer ${widget.token}',
'Content-Type': 'application/json',
};
final body = json.encode({
'conversa_id': conversaId!,
'resposta': texto.trim(),
});
try {
final response = await http.post(url, headers: headers, body: body);
if (response.statusCode == 200) {
final data = json.decode(response.body);
if (data.containsKey('pergunta')) {
// Resposta normal com uma pergunta
setState(() {
messages.add({
'papel': 'assistente',
'conteudo': data['pergunta'],
});
});
} else if (data.containsKey('tarefas')) {
// Recebeu lista de tarefas
List<String> tarefas = List<String>.from(data['tarefas']);
_exibirDialogoTarefas(tarefas);
} else {
// Mensagem inesperada
setState(() {
messages.add({
'papel': 'assistente',
'conteudo': 'Houve um erro ao processar a resposta do assistente.',
});
});
}
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content:
Text('Erro ao enviar mensagem: ${response.statusCode}')),
);
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Erro: ${e.toString()}')),
);
} finally {
setState(() {
isLoading = false;
});
}
}
void _exibirDialogoTarefas(List tarefas) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('O que deseja fazer?'),
content: SingleChildScrollView(
child: ListBody(
children: [
Text('O chat gerou a seguinte lista de tarefas:'),
SizedBox(height: 10),
...tarefas.map((tarefa) => Text('- $tarefa')).toList(),
],
),
),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
// Continuar o chat
},
child: Text('Continuar o chat'),
),
TextButton(
onPressed: () async {
Navigator.pop(context);
// Criar nova lista de tarefas apagando as tarefas anteriores
await _criarListaDeTarefas(tarefas, apagarAnterior: true);
},
child: Text('Criar nova lista de tarefas'),
),
TextButton(
onPressed: () async {
Navigator.pop(context);
// Adicionar as tarefas à lista existente
await _criarListaDeTarefas(tarefas, apagarAnterior: false);
},
child: Text('Adicionar à lista existente'),
),
],
),
);
}
Future _criarListaDeTarefas(List tarefas, {required bool apagarAnterior}) async {
// Primeiro, permitir ao usuário selecionar em qual lista adicionar as tarefas
// Buscar todas as listas de tarefas do usuário
final taskListsUrl = Uri.parse('https://barra.cos.ufrj.br/rest/tarefasv2?email=eq.${widget.email}');
final taskListsHeaders = {
'Authorization': 'Bearer ${widget.token}',
'accept': 'application/json',
};
List<Map<String, dynamic>> taskLists = [];
try {
final response = await http.get(taskListsUrl, headers: taskListsHeaders);
if (response.statusCode == 200) {
final data = json.decode(response.body);
taskLists = List<Map<String, dynamic>>.from(data);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Erro ao carregar listas de tarefas: ${response.statusCode}')),
);
return;
}
// Se o usuário não tiver listas de tarefas, pedir para criar uma nova
if (taskLists.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Você não tem nenhuma lista de tarefas.')),
);
return;
}
// Exibir um diálogo para o usuário escolher a lista de tarefas
String? selectedTaskListId = await showDialog(
context: context,
builder: (context) => SimpleDialog(
title: Text('Selecione uma lista de tarefas'),
children: taskLists
.map((taskList) => SimpleDialogOption(
onPressed: () {
Navigator.pop(context, taskList['id'].toString());
},
child: Text(taskList['titulo'] ?? 'Lista ${taskList['id']}'),
))
.toList(),
),
);
if (selectedTaskListId == null) {
return; // Usuário cancelou
}
// Obter as tarefas atuais da lista selecionada
List<Map<String, dynamic>> tarefasAtuais = [];
if (!apagarAnterior) {
// Buscar tarefas existentes
final tarefasUrl = Uri.parse(
'https://barra.cos.ufrj.br/rest/tarefasv2?select=valor&id=eq.$selectedTaskListId');
final tarefasHeaders = {
'Authorization': 'Bearer ${widget.token}',
'Content-Type': 'application/json',
};
final response = await http.get(tarefasUrl, headers: tarefasHeaders);
if (response.statusCode == 200) {
final data = json.decode(response.body);
if (data.isNotEmpty) {
tarefasAtuais = List<Map<String, dynamic>>.from(data[0]['valor'] ?? []);
}
}
}
// Preparar a lista atualizada de tarefas
List<Map<String, dynamic>> novasTarefas = tarefas
.map((tarefa) => {
'titulo': tarefa,
'concluida': false,
'isBeingDeleted': false,
})
.toList();
if (!apagarAnterior) {
novasTarefas = [...tarefasAtuais, ...novasTarefas];
}
// Atualizar as tarefas no servidor
final updateUrl = Uri.parse(
'https://barra.cos.ufrj.br/rest/tarefasv2?id=eq.$selectedTaskListId');
final updateHeaders = {
'Authorization': 'Bearer ${widget.token}',
'Content-Type': 'application/json',
};
final body = json.encode({
'valor': novasTarefas,
});
final updateResponse =
await http.patch(updateUrl, headers: updateHeaders, body: body);
if (updateResponse.statusCode != 204) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'Erro ao atualizar tarefas: updateResponse.statusCode{updateResponse.body}')),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Lista de tarefas atualizada com sucesso!')),
);
}
}
It seems you're encountering a 400 Bad Request error when trying to create a new task list in your Flutter app. The 400 error indicates that the server is unable to process the request due to a client-side error, often related to the request syntax or the data being sent.
Let's focus on the _createNewTaskList function in your TaskListsPage class where you make the POST request to create a new task list.
Here's the relevant part of your code:
Future<void> _createNewTaskList(String title) async {
if (title.trim().isEmpty) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('O título não pode ser vazio.')));
return;
}
final url = Uri.parse('https://barra.cos.ufrj.br/rest/tarefasv2');
final headers = {
'Authorization': 'Bearer ${widget.token}',
'Content-Type': 'application/json',
};
final body = json.encode({
'email': widget.email,
'titulo': title,
'valor': [],
'atributos': {},
});
try {
final response = await http.post(url, headers: headers, body: body);
if (response.statusCode == 201) {
_fetchTaskLists();
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Lista criada com sucesso!')));
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Erro ao criar lista de tarefas: ${response.statusCode}')),
);
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Erro: ${e.toString()}')),
);
}
}
Possible Causes and Solutions:
Incorrect Request Body Format:
The server might expect the request body in a different format or might be missing required fields.
Solution: Verify the API documentation to confirm the required fields and their expected formats. Ensure that the fields email, titulo, valor, and atributos are correctly named and formatted.
Missing or Incorrect Headers:
The Accept header is missing, and the server might expect it.
Solution: Add the 'Accept': 'application/json' header to your request headers.
Modify your error handling to print and display the response body when the status code isn't 201. This can reveal server-side error messages.
if (response.statusCode == 201) {
// Success handling
} else {
print('Error ${response.statusCode}: ${response.body}');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Erro ao criar lista de tarefas: ${response.statusCode} - ${response.body}')),
);
}
Validate the Request Body Against the API Specification:
Ensure that the JSON keys and their corresponding values in your request body match exactly what the API expects.
Test the API Endpoint Using Postman or cURL:
Use a tool like Postman to send a request to the endpoint with the same headers and body. This can help determine if the issue is with the client code or the server.
Here's how you might set up the request in Postman:
See if the server accepts this request or returns an error.
Check the Authorization Token:
Ensure that widget.token is correctly set and not expired.
You can print the token to verify:
print('Token: ${widget.token}');
Confirm Field Requirements:
Example of Updated Error Handling with Detailed Logging:
try {
final response = await http.post(url, headers: headers, body: body);
if (response.statusCode == 201) {
_fetchTaskLists();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Lista criada com sucesso!')));
} else {
print('Error ${response.statusCode}: ${response.body}');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Erro ao criar lista de tarefas: ${response.statusCode} - ${response.body}')),
);
}
} catch (e) {
print('Exception: $e');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Erro: ${e.toString()}')),
);
}
Additional Tips:
Ensure Correct Data Types:
Verify that all fields in the request body have the correct data types. For example, if valor should be null instead of an empty list when there are no tasks.
Handle SSL Certificates:
If you're testing on an emulator or device, make sure that SSL certificates are properly handled. Self-signed certificates can cause network requests to fail.
Check Network Connectivity:
Ensure that your device or emulator has network access and can reach the server.
Test with Sample Data:
Try using hardcoded sample data to rule out issues with dynamic variables.
final body = json.encode({
'email': 'test@example.com',
'titulo': 'Test List',
'valor': [],
'atributos': {},
});
Use a Network Inspector:
Tools like Charles Proxy or Flutter's DevTools can help you inspect network traffic and verify the exact requests being sent.
Conclusion:
By adding the missing 'Accept': 'application/json' header, inspecting the response body, and verifying the request data against the server's expectations, you should be able to identify and fix the issue causing the 400 Bad Request error.
If you continue to experience issues, please provide the error message from the response body after implementing the enhanced error handling. This information can help pinpoint the exact cause of the problem.
Feel free to update me with any new details or error messages, and I'll be happy to assist you further.
Not yet included in a published release.
Some APIs require certain fields to be non-empty or have specific formats.
For example, if valor must have a specific structure or atributos must not be empty, this could cause the server to reject the request.
Try removing valor and atributos from the request body or ensuring they match the expected structure.
final body = json.encode({
'email': widget.email,
'titulo': title,
// 'valor': [],
// 'atributos': {},
});
Or, if valor is expected to be an array of specific objects, you might need to adjust accordingly.
Check for Encoding Issues:
Ensure that the json.encode function is correctly encoding your data.
If any of the values contain special characters, they might need to be properly escaped or encoded.
Server-Side Logs:
If you have access to the server or API logs, check them for any error messages corresponding to your requests.