Error while running Dart list

Asked

Viewed 143 times

2

I am trying to make a list in Dart/flutter, however I am getting the following error while running the app screen.

inserir a descrição da imagem aqui

Repository class:

chamarGetGaiola(String usuario, String token) async {
  http.Response response = await http.get(
  urlAPI + "/GaiolasDisponiveis?usuario=$usuario&token=$token",
  headers: {"Content-type": "application/json; charset=UTF-8"},
);

if (response.statusCode.toString() == "200") {
  List<dynamic> retorno = json.decode(response.body);

  List<Gaiola> lista = List<Gaiola>();

  for (final item in retorno) {
    Gaiola novoItem = Gaiola();
    novoItem.GaiolaId = item["gaiolaId"];
    novoItem.Nome = item["nome"];
    lista.add(novoItem);
  }


  return lista;

  // print("Resposata usuário: $usuario $senha $token");

} 

Class of the Cage:

class Gaiola {

int GaiolaId;
String Nome;

}

Class to assemble the list.

import 'package:projeto/Caixa.dart';
import 'package:flutter/material.dart';
import 'package:projeto/global.dart' as gv;
import 'dart:convert';
import 'Gaiola.dart';
import 'Repositorio.dart';

class Aspirar extends StatefulWidget {
String caixa;

 @override
 _AspirarState createState() => _AspirarState();
  }



    class _AspirarState extends State<Aspirar> {



     Repositorio repositorio = Repositorio();

     TextEditingController campoQtdAspirada = TextEditingController();
     Gaiola gaiola;




    @override
    Widget build(BuildContext context) {

    List<Gaiola> listaGaiola = repositorio.chamarGetGaiola(gv.usuarioLogado, 
    gv.token);

    return Scaffold(
    appBar: AppBar(
      title:
          Text("Aspirar Caixa ${gv.codigoQrCodeCapturado.toUpperCase()}"),
      backgroundColor: Color(0xffccffcc),
    ),
    backgroundColor: Color(0xff263238),
    body: Column(
      children: <Widget>[
        Text(
          gv.codigoQrCodeCapturado.toUpperCase(),
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.white,
            fontSize: 25,
          ),
        ),
        Image.asset(
          "imagens/caixa.png",
          width: 240,
        ),
        Padding(
          padding: EdgeInsets.all(32),
          child: TextField(
            style: TextStyle(color: Colors.white),
            keyboardType: TextInputType.number,
            decoration: InputDecoration(
              labelText: "Quantidade Aspirada",
              labelStyle: TextStyle(fontSize: 20, color: Color(0xffccffcc)),
            ),
            controller: campoQtdAspirada,
          ),
        ),
        Container(
            child: DropdownButton<Gaiola>(
          items: listaGaiola.map((Gaiola gaiola) {
            return new DropdownMenuItem<Gaiola>(
              value: gaiola,
              child: new Text(
                gaiola.Nome,
                style: new TextStyle(color: Colors.black),
              ),
            );
          }).toList(),
          onChanged: (Gaiola value) {
            setState(() {
              gaiola = value;
            });
          },
          hint: Text(
            'Selecionar Gaiola',
          ),
          value: gaiola,
          underline: Container(
            decoration: const BoxDecoration(
                border: Border(
              bottom: BorderSide(color: Color(0xffccffcc)),
            )),
          ),
          style: TextStyle(
            fontSize: 20,
            color: Colors.black,
          ),
          iconEnabledColor: Color(0xffccffcc),
          iconSize: 20,
        )),
        Padding(
          padding: EdgeInsets.only(top: 16, bottom: 10),
          child: RaisedButton(
            child: Text(
              "Confirmar Aspiração",
              style: TextStyle(color: Colors.black, fontSize: 20),
            ),
            color: Color(0xffccffcc),
            padding: EdgeInsets.fromLTRB(32, 16, 32, 16),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(32)),
            onPressed: () {
              print(
                  "Combo digitado: ${campoQtdAspirada.text}, GaiolaId: ${gaiola.GaiolaId}");
            },
          ),
        ),
      ],
    ));
     }
     }

inserir a descrição da imagem aqui

  • Reading your problem again, I think my answer will not help you much. Improve your question EDITE her and put what kind of the return of this method chamarGetGaiola and also put the code where you use the method.

  • @Matheusribeiro as requested, this is the structure of the app on which I’m trying to create a list of my API returns.

1 answer

5


You have only missed the return of your method chamarGetGaiola, do so:

Future<List<Gaiola>> chamarGetGaiola(String usuario, String token) async {
  ...
}

But as your method will return one Future you will need to use the FutureBuilder, Modify your cage combo as follows

Container(
      child: FutureBuilder(
        future: repositorio.chamarGetGaiola(gv.usuarioLogado, gv.token),
        builder: (context, snapshot) {
          if (!snapshot.hasData)
            return Container();

          return DropdownButton<Gaiola>(
          items: snapshot.data.map((Gaiola gaiola) {
            return new DropdownMenuItem<Gaiola>(
              value: gaiola,
              child: new Text(
                gaiola.Nome,
                style: new TextStyle(color: Colors.black),
              ),
            );
          }).toList(),
          onChanged: (Gaiola value) {
            setState(() {
              gaiola = value;
            });
          },
          hint: Text(
            'Selecionar Gaiola',
          ),
          value: gaiola,
          underline: Container(
            decoration: const BoxDecoration(
                border: Border(
              bottom: BorderSide(color: Color(0xffccffcc)),
            )),
          ),
          style: TextStyle(
            fontSize: 20,
            color: Colors.black,
          ),
          iconEnabledColor: Color(0xffccffcc),
          iconSize: 20,
        );
        }
      )
    )

And so you won’t need to use it anymore

List<Gaiola> listaGaiola = repositorio.chamarGetGaiola(gv.usuarioLogado, 
    gv.token);

Note: I don’t have Flutter on the computer right now, so I didn’t get to test, maybe I need to do some modification.

Why use Futurebuilder?

As the request made to your API is asynchronous and the data will be received at another time it is necessary that your method return one Future<T>.

The FutureBuilder will await this call and as soon as it is finalized, will redesign the Widget that it contains.

I did a validation if (!data.hasData) return Container();, this validation serves to ensure that when the FutureBuilder is waiting for the API response he draws a Container "null" thus occupying no space and becoming imperceptible to the user.

  • Ball show Matheus, I’m just caught in the method you used just above the .map. When I called it gives me an error saying error: The method 'Map' isn’t defined for the class 'Asyncsnapshot'.

  • 1

    The AsyncSnapshot doesn’t even have the Map, I forgot a part hahaha I’ve adjusted, check the answer again, the right is snpshot.data

  • Matheus ball show, it worked the part of the app screen, but when hit my repository where we added the Future<List<Cage>>chamarGetGaiola(String usuario, String token) async it gives the following error: type 'List<Dynamic>' is not a subtype of type 'List<Dropdownmenuitem<Gaiola>' Cara me sorry it is that I am completely frustrated that I did not get this and not counting that I am starting rsrs. I’ll put the bug image for you above.

  • Cara worked well here, in my class I am working what mounts the list added after the snapshot.data.map the <Dropdownmenuitem<Cage>> being as follows items: snapshot.data.map<Dropdownmenuitem<Cage>>(cage) {... !

  • 1

    That’s what I was gonna suggest!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.