Good afternoon! I have a problem with the following code, as it throws out this error══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
The following assertion was thrown during performResize():
Vertical viewport was given unbounded height.
Viewports expand in the scrolling direction to fill their container. In this case, a vertical
viewport was given an unlimited amount of vertical space in which to expand. This situation
typically happens when a scrollable widget is nested inside another scrollable widget.
If this widget is always nested in a scrollable widget there is no need to use a viewport because
there will always be enough vertical space for the children. In this case, consider using a Column
or Wrap instead. Otherwise, consider using a CustomScrollView to concatenate arbitrary slivers into
a single scrollable. import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:collection';
Future<Map<String,dynamic>> fazerLogin(String email, String senha) async {
// URL do endpoint
final url = Uri.https('barra.cos.ufrj.br:443', '/rest/rpc/fazer_login');
// Headers da requisição
final Map<String,String> headers = {
'accept': 'application/json',
'Content-Type': 'application/json',
};
// Corpo da requisição (JSON)
final Map<String,String> body = {
'email': email,
'senha': senha,
};
// Converte o body para JSON
final String jsonBody = json.encode(body);
try {
// Realiza a requisição POST
final response = await http.post(url, headers: headers, body: jsonBody);
final decodedResponse = json.decode(response.body);
// Verifica o código de status da resposta
if (response.statusCode == 200) {
// Sucesso na requisição
final jwt = decodedResponse['token'];
return {
'login':true,
'token':jwt
};
} else {
// Erro na requisição
//print('Erro: ${response.statusCode} - ${response.body}');
final erro = decodedResponse['message'];
return {
'login':false,
'erro': erro
};
}
} catch (e) {
// Tratamento de exceções
//print('Ocorreu um erro: ${e.toString()}');
return {
'login':false
};
}
}
Future<Map<String,dynamic>> fazerCadastro(String nome, String email, String celular, String senha) async {
// URL do endpoint
final url = Uri.https('barra.cos.ufrj.br:443', '/rest/rpc/registra_usuario');
// Headers da requisição
final Map<String,String> headers = {
'accept': 'application/json',
'Content-Type': 'application/json',
};
// Corpo da requisição (JSON)
final Map<String,String> body = {
'nome': nome,
'email': email,
'celular': celular,
'senha': senha,
};
// Converte o body para JSON
final String jsonBody = json.encode(body);
try {
// Realiza a requisição POST
final response = await http.post(url, headers: headers, body: jsonBody);
final decodedResponse = json.decode(response.body);
// Verifica o código de status da resposta
if (response.statusCode == 200) {
// Sucesso na requisição
return {
'cadastro': true,
};
} else {
// Erro na requisição
//print('Erro: ${response.statusCode} - ${response.body}');
return {
'cadastro': false,
'erro': decodedResponse['message']
};
}
// Método para criar um objeto Task a partir de um mapa (vindo de JSON)
factory Task.fromJson(Map<String, dynamic> json) {
return Task(
title: json['title'],
isCompleted: json['isCompleted'],
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
final String email;
final String token;
Future salvarLista(String email, String? jwt, List taskList) async {
// URL do endpoint
final url = Uri.https('barra.cos.ufrj.br:443', '/rest/tarefas');
if (jwt == null){
//print('Token inválido');
}
final List taskJsonList = taskList.map((task) => task.toJson()).toList();
// Headers da requisição
final Map<String,String> headers = {
'accept': 'application/json',
'Content-Type': 'application/json',
'Authorization':'Bearer $jwt',
};
// Corpo da requisição (JSON)
final Map<String,dynamic> body = {
'email': email,
'valor': taskJsonList
};
// Converte o body para JSON
final String jsonBody = json.encode(body);
try {
// Realiza a requisição POST
final deletion = await http.delete(url, headers: headers, body: jsonBody);
if (deletion.statusCode == 401){
final decodedDeletion = json.decode(deletion.body);
if (decodedDeletion['code'] == "PGRST301"){
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => LoginPage(title: 'Login', errorMessage: 'O token expirou. Por favor, faça login novamente.')),
(Route route) => false,
);
}
}
final response = await http.post(url, headers: headers, body: jsonBody);
// Verifica o código de status da resposta
if (response.statusCode == 201) {
// Sucesso na requisição
} else {
//print('Erro: ${response.statusCode} - ${response.body}');
}
} catch (e) {
//print('Ocorreu um erro: ${e.toString()}');
}
}
Future getLista(String? jwt) async {
final url = Uri.https('barra.cos.ufrj.br:443', '/rest/tarefas');
if (jwt == null){
//print('Token inválido');
}
// Headers da requisição
final Map<String,String> headers = {
'accept': 'application/json',
'Content-Type': 'application/json',
'Authorization':'Bearer $jwt',
};
try {
// Realiza a requisição GET
final response = await http.get(url, headers: headers);
// Verifica o código de status da resposta
if (response.statusCode == 200) {
// Sucesso na requisição
final decodedResponse = json.decode(response.body);
List taskListFetched = decodedResponse[0]['valor'];
List<Task> taskListTasks = [];
for (var i=0;i<taskListFetched.length;i++){
taskListTasks.add(Task.fromJson(taskListFetched[i]));
}
setState(() {
taskList = taskListTasks;
});
} else {
//print('Erro: ${response.statusCode} - ${response.body}');
}
} catch (e) {
//print('Ocorreu um erro: ${e.toString()}');
}
}
void _addTask(String st) {
setState(() {
if (st.trim().isNotEmpty) {
for (var x = 0; x < taskList.length; x++) {
if (taskList[x].title == st.trim()) {
return;
}
}
final task = Task(title: st.trim());
taskList.add(task);
_sortTaskList();
textController.clear();
}
});
salvarLista(email, token, taskList);
}
void _sortTaskList() {
taskList.sort((a, b) {
if (a.isCompleted == b.isCompleted) {
return 0;
} else if (a.isCompleted) {
return 1;
} else {
return -1;
}
});
}
class TaskItemWidget extends StatelessWidget {
final Task task;
final int index;
final bool isBeingDeleted;
final Function(int) onToggleCompletion;
final Function(int) onDeleteTask;
final Function(String) onUndoDelete;
@override
State createState() => _LoginPageState();
}
class _LoginPageState extends State {
final textControllerEmail = TextEditingController();
final textControllerSenha = TextEditingController();
String? message; // Para armazenar a mensagem
@override
State createState() => _SignUpPageState();
}
class _SignUpPageState extends State {
final textControllerNome = TextEditingController();
final textControllerEmail = TextEditingController();
final textControllerCelular = TextEditingController();
final textControllerSenha = TextEditingController();
final textControllerConfirmarSenha = TextEditingController();
String? message;
class CalloutPainter extends CustomPainter {
final double triangleSize;
final double triangleHeight;
final String position;
final Color backgroundColor;
final bool isLeft; // Define se o balão é da esquerda ou direita
final Path balloonPath = Path();
// Definir o corpo do balão (retângulo arredondado)
final double margin = 10;
final double radius = 8;
final double bodyHeight = size.height - triangleHeight - margin;
balloonPath.addRRect(RRect.fromRectAndRadius(
Rect.fromLTWH(margin, margin, size.width - 2 * margin, bodyHeight),
Radius.circular(radius),
));
// Desenhar a seta na parte de baixo com inclinação para fora
final Path trianglePath = Path();
if (position == "left") {
// Seta no lado esquerdo inferior, inclinada para a esquerda (obtusa)
trianglePath.moveTo(
margin + 10, bodyHeight + margin); // Base esquerda da seta
trianglePath.lineTo(margin + 10 + triangleSize,
bodyHeight + margin); // Base direita da seta
trianglePath.lineTo(
margin - 10, size.height); // Ponta da seta inclinada para fora
} else if (position == "right") {
// Seta no lado direito inferior, inclinada para a direita (obtusa)
trianglePath.moveTo(size.width - margin - 10 - triangleSize,
bodyHeight + margin); // Base esquerda da seta
trianglePath.lineTo(size.width - margin - 10,
bodyHeight + margin); // Base direita da seta
trianglePath.lineTo(size.width + 10 - margin,
size.height); // Ponta da seta inclinada para fora
} else {
// Seta no centro inferior (isósceles)
double centerX = (size.width - triangleSize) / 2;
trianglePath.moveTo(
centerX, bodyHeight + margin); // Base esquerda da seta
trianglePath.lineTo(
centerX + triangleSize, bodyHeight + margin); // Base direita da seta
trianglePath.lineTo(
centerX + triangleSize / 2, size.height); // Ponta da seta (centro)
}
balloonPath.addPath(trianglePath, Offset.zero);
// Desenhar o balão e a seta
canvas.drawShadow(balloonPath, Colors.black, 6, false);
canvas.drawPath(balloonPath, paint);
class Callout extends StatelessWidget {
final Widget child;
final double triangleSize;
final double triangleHeight;
final String position;
final Color backgroundColor;
final bool isLeft;
Vertical viewport was given unbounded height.
Viewports expand in the scrolling direction to fill their container. In this case, a vertical viewport was given an unlimited amount of vertical space in which to expand. This situation typically happens when a scrollable widget is nested inside another scrollable widget.
This error commonly occurs in Flutter when a scrollable widget (like ListView, SingleChildScrollView, etc.) is placed within a widget that doesn't constrain its size, like a Column without specifying the height constraints for its children. As a result, the scrollable widget doesn't know how much space it can take, leading to an unbounded height.
In your code, within the ChatPage widget, you have a Column that contains a ListView.builder and a Padding containing your message input field:
The ListView.builder inside a Column without any height constraints is causing the error because Flutter cannot determine the height of the ListView.
To fix this issue, you need to wrap your ListView.builder with an Expanded widget. The Expanded widget tells Flutter to take up all remaining space within the parent widget (in this case, the Column), giving the ListView the bounded height it needs.
By wrapping ListView.builder with Expanded, you're telling Flutter that the ListView should take up the remaining space within the Column. This provides the necessary bounded height.
Additionally, make sure your itemBuilder of the ListView.builder returns widgets properly. Since you're using if and else statements, ensure that you're returning widgets in both cases.
In your original code, it seems that within the itemBuilder, you are not returning any widget; instead, you're just calling methods like Align and SizedBox without wrapping them in a return statement. This might also cause issues.
Here's how you can adjust the itemBuilder to ensure it returns widgets: