首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >不是类型'(String,dynamic) => MapEntry<dynamic,dynamic>‘的“transform”的子类型)

不是类型'(String,dynamic) => MapEntry<dynamic,dynamic>‘的“transform”的子类型)
EN

Stack Overflow用户
提问于 2020-10-07 12:35:11
回答 2查看 9.5K关注 0票数 1

我正在从服务器上获取一些产品,但我得到了一个错误,声明为,引发了另一个异常:不正确地使用ParentDataWidget。AsyncSnapshot(ConnectionState.waiting,null,type‘(动态) => ProductsModel’)不是'(String,dynamic) => MapEntry‘of’transform‘的子类型。

代码语言:javascript
复制
Incorrect use of ParentDataWidget.
The ParentDataWidget Flexible(flex: 1) wants to apply ParentData of type FlexParentData to a RenderObject, which has been set up to accept ParentData of incompatible type ParentData.

Usually, this means that the Flexible widget has the wrong ancestor RenderObjectWidget. Typically, Flexible widgets are placed directly inside Flex widgets.
The offending Flexible is currently placed inside a RepaintBoundary widget.

The ownership chain for the RenderObject that received the incompatible parent data was:
  RichText ← Text ← FutureBuilder<List<ProductsModel>> ← Container ← Flexible ← RepaintBoundary ← IndexedSemantics ← NotificationListener<KeepAliveNotification> ← KeepAlive ← AutomaticKeepAlive ← ⋯
When the exception was thrown, this was the stack: 
#0      RenderObjectElement._updateParentData.<anonymous closure> (package:flutter/src/widgets/framework.dart:5689:11)
#1      RenderObjectElement._updateParentData (package:flutter/src/widgets/framework.dart:5705:6)
#2      ParentDataElement._applyParentData.applyParentDataToChild (package:flutter/src/widgets/framework.dart:4939:15)
#3      ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4600:14)
#4      ParentDataElement._applyParentData.applyParentDataToChild (package:flutter/src/widgets/framework.dart:4942:15)
...
Another exception was thrown: Incorrect use of ParentDataWidget.
AsyncSnapshot<List<ProductsModel>>(ConnectionState.waiting, null, type '(dynamic) => ProductsModel' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform')

这是我的ProductModel课

代码语言:javascript
复制
class ProductsModel {
  String adid;
  String adsubcatid;
  String aduserid;
  String adname;
  String adcoverimg;
  String addesc;
  String adsPrice;
  String adsLocation;
  String createdDate;
  String userName;
  String images;

  ProductsModel(
      {this.adid,
        this.adsubcatid,
        this.aduserid,
        this.adname,
        this.adcoverimg,
        this.addesc,
        this.adsPrice,
        this.adsLocation,
        this.createdDate,
        this.userName,
        this.images});

  factory ProductsModel.fromJson(Map<String, dynamic> json) {
    return ProductsModel(
      adid: json['adid'],
      adsubcatid: json['adsubcatid'],
      aduserid: json['aduserid'],
      adname: json['adname'],
      adcoverimg: json['adcoverimg'],
      addesc: json['addesc'],
      adsPrice: json['ads_price'],
      adsLocation: json['ads_location'],
      createdDate: json['created_date'],
      userName: json['user_name'],
      images: json['images']
    );
  }
}

这是主页

代码语言:javascript
复制
@override
  void initState() {
    getProducts();
    super.initState();
  }

@override
  Widget build(BuildContext context) {
    print("Home");
    return Scaffold(
      appBar: AppBar(
        leading: Image.asset('assets/images/ic_logo.png'),
        actions: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: FlatButton.icon(
              onPressed: () {},
              icon: Icon(Icons.location_on),
              label: Text('Mysuru, India'),
              textColor: Colors.white,
            ),
          ),
        ],
      ),
      body: CustomScrollView(
        slivers: [
          SliverToBoxAdapter(
            child: SizedBox(
              child: _search(),
            ),
          ),
          SliverToBoxAdapter(
            child: SizedBox(
              child: HorizontalCategories(),
            ),
          ),
          SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              childAspectRatio: 0.7,
            ),
            delegate: SliverChildBuilderDelegate(
                (context, index) => _products(context)),
          )
        ],
      ),
    );
  }

 Widget _products(BuildContext context) {
    print("Inside products");
    return Flexible(
      child: Container(
        child: FutureBuilder<List<ProductsModel>>(
          future: _fetchProducts(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              print("Has data");
              List<ProductsModel> data = snapshot.data;
              return _productsList(data);
            } else if (snapshot.hasError) {
              print("Error");
              print(snapshot.hasError);
              print(snapshot);
              return Text('${snapshot.hasError}');
            } else {
              return Center(
                child: CircularProgressIndicator(),
              );
            }
          },
        ),
      ),
    );
  }

  Future<List<ProductsModel>> _fetchProducts() async {
    String productsUrl = Constant.productsUrl;
    Map<String, String> headers = {'Content-Type': 'application/json'};

    final response = await http.get(productsUrl, headers: headers);
    if (response.statusCode == 200) {
      var jsonResponse = json.decode(response.body);
      print(jsonResponse);
      return jsonResponse
          .map((products) => new ProductsModel.fromJson(products))
          .toList();
    } else {
      throw Exception('Failed to load Categories from API');
    }
  }

这是JsonResponse

代码语言:javascript
复制
{
    "status": true,
    "record": [
        {
            "adid": "1",
            "adsubcatid": "1",
            "aduserid": "2",
            "adname": "Ads",
            "adcoverimg": "Royal Enfield Classic 350 Images Classic 350 Photos & 360 View_files.JPG",
            "addesc": "vsv dsv  sd fds fd fdsf dsf s fds fdssfdf c sfdf sd",
            "ads_price": "3000",
            "ads_location": "mysore",
            "created_date": "06/10/2020",
            "user_name": "sunil",
            "images": "{'adsimg_img':'2.JPG'},{'adsimg_img':'3.JPG'},{'adsimg_img':'4.JPG'}"
        }
    ]
}
EN

回答 2

Stack Overflow用户

发布于 2021-02-07 14:11:28

映射函数不能应用于jsonResponse。

代码语言:javascript
复制
return jsonResponse
          .map((products) => new ProductsModel.fromJson(products))
          .toList();

JsonResponse包含应该映射到ProductsModelrecord字段中的记录。

代码语言:javascript
复制
return jsonResponse
          .record
          .map((products) => new ProductsModel.fromJson(products))
          .toList();
票数 0
EN

Stack Overflow用户

发布于 2022-03-07 14:48:31

你想要得到列表,record就是你应该瞄准的目标!

代码语言:javascript
复制
var data = jsonResponse['record'];

全api调用

代码语言:javascript
复制
  Future<List<ProductsModel>> _fetchProducts() async {
    String productsUrl = Constant.productsUrl;
    Map<String, String> headers = {'Content-Type': 'application/json'};

    final response = await http.get(productsUrl, headers: headers);
    if (response.statusCode == 200) {
      var jsonResponse = json.decode(response.body);
      var data = jsonResponse['record'];
      return data
          .map((products) => new ProductsModel.fromJson(products))
          .toList();
    } else {
      throw Exception('Failed to load Categories from API');
    }
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64244158

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档