我如何对数据Flutther使用json解码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我如何对数据Flutther使用json解码相关的知识,希望对你有一定的参考价值。

我需要有关Flutter中json解码的帮助,我无法按json的项目列出,只能列出所有项目。

我的“结果”,列出所有Json,我不能仅列出项目“图像”。

例如,如何使用screenlist.image并仅列出json的“图像”项?

在此行中为“ print(screenlist);”打印所有json,但不打印(screenlist.image),则我的futurebuilder无法工作。

我的模特:

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'] as int,
      x: json['x'] as int,
      y: json['y'] as int,
      pos: json['pos'] as int,
      id_user: json['id_user'] as int,
      image: json['image'] as String,
    );
  }

  @override
  String toString(){
    return '{ ${this.id}, ${this.x}, ${this.y}, ${this.pos}, ${this.id_user}, ${this.image} }';
  }
}


我的数据:

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);
  }
}

我的屏幕:

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> {

//  List<ScreenListModel> screenlist = new List<ScreenListModel>();

  _getListaScreen(){
    HomeListData.getListData().then((response){
      var testListaJson = jsonDecode(response.body) as List;
      List<ScreenListModel> screenlist = testListaJson.map((listaJson) => ScreenListModel.fromJson(listaJson)).toList();
//        print("testando");
        print(screenlist);
    });
  }

  @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){
                if(!snapshot.hasData)
                  return SliverToBoxAdapter(
                    child: Container(
                      height: 200,
                      alignment: Alignment.center,
                      child: CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.black),
                      ),
                    ),
                  );
                else{
                  print("testando");
                  print("");
                  return SliverToBoxAdapter(
                    child: Container(
                      height: 200,
                      alignment: Alignment.center,
                      child: CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    ),
                  );
                }
              },
            )
          ],
        )
      ],
    );
  }
}

我的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/flutter ( 3182): [{ 1, 2, 2, 0, 1, https://as1.ftcdn.net/jpg/00/66/06/80/500_F_66068078_KSdyJchbJ3KqBcdsooLKFdYhsp7fElQO.jpg }, { 2, 1, 1, 3, 1, https://as2.ftcdn.net/jpg/01/06/76/35/500_F_106763503_HVPDhqUbbJbuEpQQDes4ADOrCRGsy806.jpg }, { 3, 1, 1, 2, 1, https://as2.ftcdn.net/jpg/00/59/29/77/500_F_59297786_ANsYzqVG3q8bIdCrItkl7OJImITayvzy.jpg }, { 4, 1, 1, 1, 1, https://as2.ftcdn.net/jpg/03/29/03/25/500_F_329032512_IcHWPOA5g3sENhbV9rKz8fFIRCQVQNCY.jpg }, { 5, 1, 1, 4, 1, https://as2.ftcdn.net/jpg/03/20/43/37/500_F_320433797_B2asZKnko8B2rYQ0OaEQbHccUmD9kzjm.jpg }]
I/flutter ( 3182): [{ 1, 2, 2, 0, 1, https://as1.ftcdn.net/jpg/00/66/06/80/500_F_66068078_KSdyJchbJ3KqBcdsooLKFdYhsp7fElQO.jpg }, { 2, 1, 1, 3, 1, https://as2.ftcdn.net/jpg/01/06/76/35/500_F_106763503_HVPDhqUbbJbuEpQQDes4ADOrCRGsy806.jpg }, { 3, 1, 1, 2, 1, https://as2.ftcdn.net/jpg/00/59/29/77/500_F_59297786_ANsYzqVG3q8bIdCrItkl7OJImITayvzy.jpg }, { 4, 1, 1, 1, 1, https://as2.ftcdn.net/jpg/03/29/03/25/500_F_329032512_IcHWPOA5g3sENhbV9rKz8fFIRCQVQNCY.jpg }, { 5, 1, 1, 4, 1, https://as2.ftcdn.net/jpg/03/20/43/37/500_F_320433797_B2asZKnko8B2rYQ0OaEQbHccUmD9kzjm.jpg }]
I/flutter ( 3182): [{ 1, 2, 2, 0, 1, https://as1.ftcdn.net/jpg/00/66/06/80/500_F_66068078_KSdyJchbJ3KqBcdsooLKFdYhsp7fElQO.jpg }, { 2, 1, 1, 3, 1, https://as2.ftcdn.net/jpg/01/06/76/35/500_F_106763503_HVPDhqUbbJbuEpQQDes4ADOrCRGsy806.jpg }, { 3, 1, 1, 2, 1, https://as2.ftcdn.net/jpg/00/59/29/77/500_F_59297786_ANsYzqVG3q8bIdCrItkl7OJImITayvzy.jpg }, { 4, 1, 1, 1, 1, https://as2.ftcdn.net/jpg/03/29/03/25/500_F_329032512_IcHWPOA5g3sENhbV9rKz8fFIRCQVQNCY.jpg }, { 5, 1, 1, 4, 1, https://as2.ftcdn.net/jpg/03/20/43/37/500_F_320433797_B2asZKnko8B2rYQ0OaEQbHccUmD9kzjm.jpg }]

想!

答案

您可以尝试使用此代码:

Future<List<ScreenListModel>> _getListaScreen() async {
  var response = await HomeListData.getListData();
  var testListaJson = jsonDecode(response.body) as List;
  return testListaJson.map((listaJson) => ScreenListModel.fromJson(listaJson)).toList();
}
另一答案

太好了!在Firebase中,我确实使用了这种格式,但不适用于json,如何在json中使用?

FutureBuilder(
              future: _getListaScreen(),
              builder: (context, snapshot){
                if(!snapshot.hasData)
                  return SliverToBoxAdapter(
                    child: Container(
                      height: 200,
                      alignment: Alignment.center,
                      child: CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.black),
                      ),
                    ),
                  );
                else{
                  return SliverStaggeredGrid.count(
                      crossAxisCount: 2,
                      mainAxisSpacing: 1,
                      crossAxisSpacing: 1,
                      staggeredTiles: snapshot.data.documents.map((doc){
                        return StaggeredTile.count(doc.data['x'], doc.data['y']);
                      }
                      ).toList(),
                      children: snapshot.data.documents.mapp((doc){
                        return FadeInImage.memoryNetwork(
                          placeholder: kTransparentImage,
                          image: doc.data['image'],
                          fit: BoxFit.cover,
                        );
                      }).toList()
                  );

Erro:

I/flutter ( 3182): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 3182): The following NoSuchMethodError was thrown building FutureBuilder<List<ScreenListModel>>(dirty,
I/flutter ( 3182): state: _FutureBuilderState<List<ScreenListModel>>#0b7f6):
I/flutter ( 3182): Class 'List<ScreenListModel>' has no instance getter 'documents'.
I/flutter ( 3182): Receiver: Instance(length:5) of '_GrowableList'
I/flutter ( 3182): Tried calling: documents
I/flutter ( 3182): The relevant error-causing widget was:
I/flutter ( 3182):   FutureBuilder<List<ScreenListModel>>

以上是关于我如何对数据Flutther使用json解码的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 cURL 获取 JSON 数据并解码数据?

如何在 dart 中从服务器解码 json?

无法使用 JSONDecoder 返回或解码数据

如何使用 Codable 解码具有更改键的 json 响应?

如何在 Swift 中解码这个 JSON 数据?

如何从其他站点检索 json 数据并使用 cURL 对其进行解码?