skip to Main Content

I’m making an routine app but I’m having problems to render a list of cards in my app Flutter. The function that calls the api returns an json, ok, but my code appears to don’t work with it.

my api returns:

[{id: 1, belongs_to: 2, title: have breakfast, description_text: make my breakfast, date_time: 2023-09-16 15:46:25}]

my code

class RoutineScreen extends StatefulWidget {
  const RoutineScreen({Key? key}) : super(key: key);

  @override
  State<RoutineScreen> createState() => _RoutineScreenState();
}

class _RoutineScreenState extends State<RoutineScreen> {

  Future<List<Map<String, dynamic>>> getRoutines() async {
    var headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
    };

    var request = http.Request('POST', Uri.parse('http://localhost:8080'));

    request.bodyFields = {
      'route': 'routine_get',
      'id':'2'
    };

    request.headers.addAll(headers);

    http.StreamedResponse response = await request.send();

    if (response.statusCode == 200) {
      String responseBody = await response.stream.bytesToString();
      List<dynamic> jsonData = json.decode(responseBody);
      return jsonData.cast<Map<String, dynamic>>();
    } else {
      throw Exception('Erro na requisição. Código de status: ${response.statusCode}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FractionallySizedBox(
        widthFactor: 1.0,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 15.0,),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 10.0),
              child: Text(
                  'Olá!',
                  style: TextStyle(
                    color: primaryColor,
                    fontSize: 30.0
                  ),
              ),
            ),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 10.0),
              child: Text(
                'Sua rotina de hoje:',
                style: TextStyle(
                    fontSize: 20.0
                ),
              ),
            ),
            SizedBox(height: 20.0),
            FutureBuilder<List<Map<String, dynamic>>>(
              future: getRoutines(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                } else if (snapshot.hasError) {
                  return Center(
                    child: Text('Erro: ${snapshot.error}'),
                  );
                } else if (snapshot.hasData) {
                  List<Map<String, dynamic>> data = snapshot.data!;
                  return ListView.builder(
                    itemCount: data.length,
                    itemBuilder: (context, index) {
                      print('entrou no builder');
                      String title = data[index]['title'];
                      String text = data[index]['description_text'];
                      int id = data[index]['id'];
                      return CardRoutine(id: id, title: title, postText: text);
                    },
                  );
                } else {
                  return Center(
                    child: Text('Nenhum dado encontrado.'),
                  );
                }
              },
            ),
          ],
        ),
      ),
    );
  }
}

what can be happening here?

I tryed to debug, my code returns my necessary data, but dont enters in ListView.builder

2

Answers


  1. Have you checked your console? You’re likely having UI errors. The ListView doesn’t have a size and flutter don’t know what to do in this situation. Wrapping your ListView.builder widget with an Expanded or Flexible widget might do the job. Use Expanded if you want it to fill all the rest of your column. If this doesn’t work, try to add shrinkWrap: true. If it still doesn’t work, check your console for clues, it could be a bug with CardRoutine.

    Login or Signup to reply.
  2. I’ve found two issues in the provided code snippet.

    1. Add shrinkWrap: true in the ListView.builder.
    2. Wrap RoutineScreen() with an Expanded like this: Expanded(child: RoutineScreen()).
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search