FLUTTER ERROR - The method '[]' was called on null

Asked

Viewed 928 times

-1

I’m starting with Flutter, and I stumbled upon the mistake

The method '[]' was called on null.

I am testing an api to return the data, but I always get this error. The strange thing is that if I restart the application the error disappears and the data appears normally. This error happens in all the screens I use in the api, and in all of them I restart the application or turn the screen and open it again the error does not happen.

    List<GetItems> _item;

    Future<List<GetItems>> _getItem() async {
      List<GetItems> listItem = [];

      final response = await http.get(
          'http://192.168.1.145/crud/index.php?action=getItem&id=' + widget.id);

      if (response.statusCode == 200) {
        var decodeJson = jsonDecode(response.body);
        decodeJson.forEach((item) => listItem.add(GetItems.fromJson(item)));
        return listItem;
      } else {
        print('connection error');
      }
    }

    void initState() {
      super.initState();
      _getItem().then((map) {
        _item = map;
      });
    }

return Scaffold(
  drawer: SideMenu(),
  body: SingleChildScrollView(
    child: Column(
      children: [
        Top(title: _item[0].nome),
        Container(
          margin: EdgeInsets.only(top: 20),
          height: 250,
          width: MediaQuery.of(context).size.width - 20,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(25),
              image: DecorationImage(
                image: AssetImage('assets/img/' + _item[0].imagens),
                fit: BoxFit.fill,
              )
          ),
       ),

inserir a descrição da imagem aqui

2 answers

0


The error occurs because when the widgets tree is done, it tries to build:

AssetImage('assets/img/' + _item[0].imagens)

However _item is not initialized, that is, null. So it gives error.

You are doing the data fetch in init state and then giving a setState. Why not use a Futurebuilder?

    FutureBuilder(
      future: _getItem,
      builder: (context, snapshot) {
        if (!snapshot.hasData) return CircularProgressIndicator();
        List<GetItems> _item = snapshot.data;
        return Container(
          margin: EdgeInsets.only(top: 20),
          height: 250,
          width: MediaQuery.of(context).size.width - 20,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(25),
              image: DecorationImage(
                image: AssetImage('assets/img/' + _item[0].imagens),
                fit: BoxFit.fill,
              )),
        );
      },
    ),
  • It worked! Thank you.

0

Apparently your widget is being built faster than the API response time, and your initState does not expect an API response. That is why Futurebuilder you need to show a loading screen or "nothing" while your data is loading, once loaded you can update the status of your Widget with the loaded data list.

FutureBuilder(
  future: _getItem,
  builder: (context, snapshot) {
    if(snapshot.connectionState == ConnectionState.done){
      if(snapshot.hasError){
        /// Terminou de carregar mas com erro
      } else {
        /// Tudo ok mostre a sua lista que está dentro snapshot.data
      }
    } else {
      /// carregando informações
    }
  },
),
  • It worked! Thank you.

Browser other questions tagged

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