为啥ListItem返回null,因为后端有一个项目

Posted

技术标签:

【中文标题】为啥ListItem返回null,因为后端有一个项目【英文标题】:Why am Returning null for ListItem, since there is an item in backend为什么ListItem返回null,因为后端有一个项目 【发布时间】:2021-07-06 13:44:22 【问题描述】:

我是 Flutter 的新手,我正在使用 ListView.Builder 构建一个 listView,这里我有我的模型类,我也发布了标题数据,但它总是返回 null,我已经尝试了所有可能但没有知道为什么会发生,那里有任何解决方案,这可能真的很有帮助..

Data.dart

class Data 
  String itemId;
  String name;
  String price;
  String picture;
  String description;
  String status;

  Data(this.itemId,
    this.name,
    this.price,
    this.picture,
    this.description,
    this.status);

  Data.fromJson(Map<String, dynamic> json) 
    itemId = json['item_id'];
    name = json['name'];
    price = json['price'];
    picture = json['picture'];
    description = json['description'];
    status = json['status'];
  

  Map<String, dynamic> toJson() 
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['item_id'] = this.itemId;
    data['name'] = this.name;
    data['price'] = this.price;
    data['picture'] = this.picture;
    data['description'] = this.description;
    data['status'] = this.status;
    return data;
  

我的 Listview 类是

ListItems.dart

import 'dart:convert';

import 'package:boxmi_now/model/Data.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;

import 'ItemView.dart';

class ListItemsSuman extends StatefulWidget 
  @override
  _ListItemsSumanState createState() => _ListItemsSumanState();


class _ListItemsSumanState extends State<ListItemsSuman> 

  List<Data> listItem = [];
  var loading = false;

  Future<Null> getData() async 
    setState(() 
      loading = true;
    );

    SharedPreferences user = await SharedPreferences.getInstance();
    // ignore: non_constant_identifier_names
    var user_id = user.getString('user_id');
    // ignore: non_constant_identifier_names
    var access_token = user.getString('access_token');

    Map data = 
      "user_id": user_id,
      "access_token": access_token,
    ;

    var url = My_HTTP_URL;
    final responseData = await http.post(url, body: data);
    final decodeData = jsonDecode(responseData.body);
    print(decodeData);
    setState(() 
//here is whey i remains null
      for (Map i in decodeData) 
        listItem.add(Data.fromJson(i));
      
      loading = false;
    );
  

  @override
  void initState() 
    // TODO: implement initState
    super.initState();
    asyncMethod();
  

  Future<void> asyncMethod() async 
    await getData();
  

  @override
  Widget build(BuildContext context) 
    return Scaffold(
      body: Container(
        child: loading ? Center(child: CircularProgressIndicator()) :
        ListView.builder(
            itemCount: listItem.length,
            itemBuilder: (context, i) 
              final nDataList = listItem[i];
              return Container(
                child: InkWell(
                  onTap: () 
                    Navigator.push(
                        context, MaterialPageRoute(builder: (context) =>
                        ItemView(

                        )));
                  ,
                  child: Card(
                    child: Padding(
                      padding: EdgeInsets.all(10.0),
                      child: Column(
                        children: [
                          Text(nDataList.name),
                          Text(nDataList.price),
                          Container(
                            height: 100.0,
                            width: 100.0,
                            child: Image.network(nDataList.picture),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              );
           
        ),
      ),
    );
  

我的解码 JSON 响应被跟随

"success":true,
"data":[

"item_id":"UID-60279bce6f25d161320852660279bce6f261",
"name":"Fish 1",
"price":"\u20b9100.00",
"picture":"ea8ccfeb468955a9a1b4f82377f59298ce368209.9j",
"description":"This is fish. And nice one",
"status":"1"
,

"item_id":"UID-60279bc1d63a3161320851360279bc1d63a9",
"name":"Fish 2",
"price":"\u20b9100.00",
"picture":"f1c8601cbc9ff0940f4a5fc8d3c1f608cf460de0.9j",
"description":"This is fish. And nice one",
"status":"1"
]
,"code":200

在控制台中,我是这样的

E/flutter (15241): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>'
E/flutter (15241): #0      _ListItemsSumanState.getData.<anonymous closure> (package:boxmi_now/Screens/ListItemsSuman.dart:40:21)
E/flutter (15241): #1      State.setState (package:flutter/src/widgets/framework.dart:1267:30)
E/flutter (15241): #2      _ListItemsSumanState.getData (package:boxmi_now/Screens/ListItemsSuman.dart:39:5)
E/flutter (15241): <asynchronous suspension>
E/flutter (15241): #3      _ListItemsSumanState.asyncMethod (package:boxmi_now/Screens/ListItemsSuman.dart:55:5)
E/flutter (15241): <asynchronous suspension>
E/flutter (15241): 

【问题讨论】:

从您的 getData 方法中,您不会返回任何内容。也返回您的 listItem。 【参考方案1】:

decodeData 是一个地图。而且您正在尝试使用 for...in 遍历 Map,这是不可能的。首先,从 decodeData

中检索数据
List<dynamic> data = decodeData["data"] as List;

然后就可以循环遍历数据列表了:

listitem = data.map((item) => Data.fromJson(item)).toList();

【讨论】:

我做了以下事情,所以得到了像E/flutter ( 9682): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: type 'List&lt;dynamic&gt;' is not a subtype of type 'List&lt;Map&lt;String, dynamic&gt;&gt;' E/flutter ( 9682): #0 _ListItemsSumanState.getData.&lt;anonymous closure&gt; (package:boxmi_now/Screens/ListItemsSuman.dart:42:34) E/flutter ( 9682): #1 State.setState (package:flutter/src/widgets/framework.dart:1267:30) E/flutter ( 9682): #2 _ListItemsSumanState.getData这样的异常 我已经更新了我的答案。尝试更新的解决方案。

以上是关于为啥ListItem返回null,因为后端有一个项目的主要内容,如果未能解决你的问题,请参考以下文章

Apollo/Graphql,Postgres - 为啥这个查询返回 null? [复制]

php获取数据为啥curl获取不完整

为啥 java String类 中的valueOf(Object obj) 空时返回的是"null"而不是null

ListItem 圆盘显示在垂直底部

java 泛型函数需要返回Integer 我返回null 为啥报空指针异常

我:正在尝试使用 STR_TO_DATE 但为啥返回 null?