当前位置: 首页 > 知识库问答 >
问题:

不是转换类型的子类型(字符串,动态)=>MapEntry)

廖琪
2023-03-14

我取一些产品从服务器,但我得到了一个错误,说明另一个例外被抛出:不正确使用家长DataWidget。同步快照

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课程

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

这是主页

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

这是JsonResorts

{
    "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'}"
        }
    ]
}

共有1个答案

潘琪
2023-03-14

映射函数不能应用于jsonResponse。

return jsonResponse
          .map((products) => new ProductsModel.fromJson(products))
          .toList();

在记录字段中包含记录,这些记录应该映射到产品模型。

return jsonResponse
          .record
          .map((products) => new ProductsModel.fromJson(products))
          .toList();
 类似资料:
  • 这是显示类型列表动态不是类型映射字符串动态的子类型“现在当我运行模拟器时,显示”类型列表动态不是类型映射字符串动态的子类型“在我的模拟器上,我如何修复它? 现在我想创建关于查找api id的程序,从我的模拟器中使用文本字段和按钮,当我把一些数字和单击按钮时,会显示该ID的数据或标题,但我只是初学者,所以如果有人认为我的代码是正确的或不正确的或者你有推荐请告诉我 My JSON JSON代码 应用程

  • 我想从Firestore获取会议并将其映射到以下模型中: 从Firestore获取文档,然后在iterable上调用< code>fromJson,但会引发一个异常: 当我进入生成的< code>meeting.g.dart时,就是这一行导致了错误 为了解决此问题,我尝试在模型中从 DateTime 更改为 Timestamp,但随后显示以下生成错误: 你能告诉我你如何解决这个问题吗?有没有另一种

  • 我得到这个错误列表是不是一个类型的子类型字符串在类型铸造,目前我正在发送的形式数据在体内,因为服务器不接受任何原始请求 //服务器响应,表示服务器成功接收并返回状态200

  • 当我运行我的代码时,它返回了错误:类型“Future”不是类型转换中“List”类型的子类型。我该如何修复它?它是在我从Firebase获取数据之前匹配引擎运行的?我试图将wait添加到List demoProfiles=getdata()作为wait List;但它返回错误。我真的是新手,这个问题已经困扰了我一整天。请帮帮我

  • 我有错误从标题时试图这样做 > 我创建了@JsonSerialiazable()类来处理json 然后,在调用http时。get(),我执行以下操作: map变量如下所示: 当调用$MyResponseFromJson(json)时,当它试图从我的响应中执行(json['a']as List)时,它会给出一个错误。g、 构建运行程序生成的dart文件。 我如何修复错误? 谢啦

  • 我对flatter是个新手,我想呈现一个ListView。但是我犯了一个错误。 我有3个模型课: 主题、主题和内容。 这是模型文件: 这是文件: 问题出现在。 错误消息是: