Error converting firebase to json with flutter Dart

Asked

Viewed 93 times

-2

Good afternoon, you guys, This firebase screen was working perfectly, but as I created an API and am migrating to json, I am not being able to convert this screen and I would like your help!

The model:

class ScreenListModel {
  final int id;
  final int x;
  final int y;
  final int pos;
  final int id_user;
  final String image;

  ScreenListModel({this.id, this.x, this.y, this.pos, this.id_user, this.image});

  factory ScreenListModel.fromJson(Map<String, dynamic> json) {
    return ScreenListModel(
      id: json['id'],
      x: json['x'],
      y: json['y'],
      pos: json['pos'],
      id_user: json['id_user'],
      image: json['image'],
    );
  }
}

The Dart that receives the data:

import 'package:http/http.dart' as http;

const String baseUrl = 'http://192.168.0.187/api/homescreen';

class HomeListData {
  static Future getListData() async {
    return await http.get(baseUrl);
  }
}

And the screen:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:transparent_image/transparent_image.dart';



import 'package:apppeccatidigola/datas/homescreen_data.dart';
import 'package:apppeccatidigola/models/homescreen_model.dart';
import 'package:flutter/material.dart';
import 'dart:convert';

class HomeTab extends StatefulWidget {
  @override
  _HomeTabState createState() => _HomeTabState();
}

class _HomeTabState extends State<HomeTab> {

  var screenlist = new List<ScreenListModel>();

  _getListaScreen(){
      HomeListData.getListData().then((response){
        Iterable listaScreenHome = json.decode(response.body);
        screenlist = listaScreenHome.map((model) => ScreenListModel.fromJson(model)).toList();
      });
  }

  _HomeTabState(){
    _getListaScreen();
  }

  @override
  Widget build(BuildContext context) {

    Widget _buildBodyBack() => Container(
      decoration: BoxDecoration(
          gradient: LinearGradient(
              colors: [
                Color.fromARGB(255, 211, 118, 130),
                Color.fromARGB(255, 253, 181, 168)
              ],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight
          )
      ),
    );

    return Stack(
      children: <Widget>[
        _buildBodyBack(),
        CustomScrollView(
          slivers: <Widget>[
            SliverAppBar(
              floating: true, //Some a barra
              snap: true, //com floating vai aparecendo a barra
              backgroundColor: Color.fromARGB(255, 211, 118, 130),
              pinned: true,
              elevation: 0.0,
              flexibleSpace: FlexibleSpaceBar(
                title: const Text('Novidades'),
                centerTitle: true,
              ),
            ),
            FutureBuilder(
              future: _getListaScreen(),
              builder: (context, snapshot){
                  return SliverStaggeredGrid.count( // count serve para quando se tem um numero exato
                      crossAxisCount: 2, //numero de colunas
                      mainAxisSpacing: 1,
                      crossAxisSpacing: 1,
                      //dimensões das imagens
                      staggeredTiles: screenlist.map((doc){
                        return StaggeredTile.count(doc.data['x'], doc.data['y']);
                      }
                      ).toList(),
                      children: snapshot.data.documents.map((doc){
                        return FadeInImage.memoryNetwork( //faz a imagem aparecer suavimente
                          placeholder: kTransparentImage,
                          image: doc.data['image'],
                          fit: BoxFit.cover,
                        );
                      }).toList()
                  );
              },
            )
          ],
        )
      ],
    );
  }
}

Json:

[{"id":1,"image":"https:\/\/as1.ftcdn.net\/jpg\/00\/66\/06\/80\/500_F_66068078_KSdyJchbJ3KqBcdsooLKFdYhsp7fElQO.jpg","x":2,"y":2,"pos":0,"id_user":1,"created_at":null,"updated_at":null},{"id":2,"image":"https:\/\/as2.ftcdn.net\/jpg\/01\/06\/76\/35\/500_F_106763503_HVPDhqUbbJbuEpQQDes4ADOrCRGsy806.jpg","x":1,"y":1,"pos":3,"id_user":1,"created_at":null,"updated_at":null},{"id":3,"image":"https:\/\/as2.ftcdn.net\/jpg\/00\/59\/29\/77\/500_F_59297786_ANsYzqVG3q8bIdCrItkl7OJImITayvzy.jpg","x":1,"y":1,"pos":2,"id_user":1,"created_at":null,"updated_at":null},{"id":4,"image":"https:\/\/as2.ftcdn.net\/jpg\/03\/29\/03\/25\/500_F_329032512_IcHWPOA5g3sENhbV9rKz8fFIRCQVQNCY.jpg","x":1,"y":1,"pos":1,"id_user":1,"created_at":null,"updated_at":null},{"id":5,"image":"https:\/\/as2.ftcdn.net\/jpg\/03\/20\/43\/37\/500_F_320433797_B2asZKnko8B2rYQ0OaEQbHccUmD9kzjm.jpg","x":1,"y":1,"pos":4,"id_user":1,"created_at":null,"updated_at":null}]

I believe the error lies in this code snippet: staggeredTiles: screenlist.map((doc){ Return Staggeredtile.Count(doc.data['x'], doc.data['y']);

Follow below the error:

Restarted application in 2.003ms.
I/flutter ( 3220): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 3220): The following NoSuchMethodError was thrown building FutureBuilder<dynamic>(dirty, state:
I/flutter ( 3220): _FutureBuilderState<dynamic>#3bb09):
I/flutter ( 3220): The method 'map' was called on null.
I/flutter ( 3220): Receiver: null
I/flutter ( 3220): Tried calling: map(Closure: (dynamic) => StaggeredTile)
I/flutter ( 3220): The relevant error-causing widget was:
I/flutter ( 3220):   FutureBuilder<dynamic>
I/flutter ( 3220):   file:///home/glauco/Documentos/Desenvolvimento/FlutterProjects/app_peccatidigola/lib/tabs/home_tab.dart:64:13
I/flutter ( 3220): When the exception was thrown, this was the stack:
I/flutter ( 3220): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
I/flutter ( 3220): #1      _HomeTabState.build.<anonymous closure> (package:apppeccatidigola/tabs/home_tab.dart:72:53)
I/flutter ( 3220): #2      _FutureBuilderState.build (package:flutter/src/widgets/async.dart)
I/flutter ( 3220): #3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4334:27)
I/flutter ( 3220): #4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4223:15)
I/flutter ( 3220): #5      Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
I/flutter ( 3220): #6      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5)
I/flutter ( 3220): #7      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4381:11)
I/flutter ( 3220): #8      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)

Because when I remove all the Futurebuilder Return and leave a print(screenlist.lenght) appears the amount of json, then it is pulling the data

  • It’s not working because? What mistake are you making? Help us help you, little man. EDITA your question with this information

  • I edited, added the msg error, obg Matheus by the tip.

1 answer

0

The lack of attention is one of the biggest problems, let’s analyze your code...

You call the following method in your FutureBuilder, that returns nothing...

  _getListaScreen(){
      HomeListData.getListData().then((response){
        Iterable listaScreenHome = json.decode(response.body);
        screenlist = listaScreenHome.map((model) => ScreenListModel.fromJson(model)).toList();
      });
  }

So in your FutureBuilder, you make the following call

snapshot.data.documents.map{}

As your method returns nothing, so your property snapshot will be null, is not?

Then modify your FutureBuilder as follows:

  FutureBuilder(
    future: _getListaScreen(),
    builder: (context, snapshot){
      return SliverStaggeredGrid.count( // count serve para quando se tem um numero exato
        crossAxisCount: 2, //numero de colunas
        mainAxisSpacing: 1,
        crossAxisSpacing: 1,
        //dimensões das imagens
        staggeredTiles: screenlist.map((doc){
          return StaggeredTile.count(doc.data['x'], doc.data['y']);
        }
        ).toList(),
        children: screenlist.map((doc){
          return FadeInImage.memoryNetwork( //faz a imagem aparecer suavimente
            placeholder: kTransparentImage,
            image: doc.data['image'],
            fit: BoxFit.cover,
          );
        }).toList()
      );
    },
  )

Another thing is, you’re using the FutureBuilder For what? For your method waits for nothing, change to the following:

  _getListaScreen() async {
      var response = await HomeListData.getListData()
      Iterable listaScreenHome = json.decode(response.body);
      screenlist = listaScreenHome.map((model) => ScreenListModel.fromJson(model)).toList();
      setState((){});
      });
  }

And as its method is already used in FutureBuilder remove him from initState.

For your code to be really correct, make yours _getListaScreen() return the list, and use FutureBuilder the snapshot.data instead of screenList

The errors in Flutter are almost always very clear and explanatory, read them!

Browser other questions tagged

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