- 如何解决:ParentDataWidget 使用不正确?

Posted

技术标签:

【中文标题】- 如何解决:ParentDataWidget 使用不正确?【英文标题】:- How to fix it : Incorrect use of ParentDataWidget? 【发布时间】:2021-01-22 19:30:14 【问题描述】:

我收到错误错误使用 ParentDataWidget。

并且列表第一次没有显示该项目。

ParentDataWidget Expanded(flex: 1) 想要将 FlexParentData 类型的 ParentData 应用于 RenderObject,该 RenderObject 已设置为接受 ParentData 类型不兼容的 ParentData。

通常,这意味着 Expanded 小部件具有错误的祖先 RenderObjectWidget。通常,扩展小部件直接放置在 Flex 小部件内。 有问题的 Expanded 当前放置在 ConstrainedBox 小部件内。

@override
Widget build(BuildContext context) 
 return Scaffold(
     appBar: AppBar(
       actions: <Widget>[
         IconButton(
           icon: Icon(Icons.shopping_cart),
           onPressed: () ,
         )
       ],
       backgroundColor: Colors.green,
     ),
     drawer: Drawer(
       child: AppDrawer(),
     ),
     body: SingleChildScrollView(
       child: ConstrainedBox(
         constraints: BoxConstraints(),
         child: Column(
           children: <Widget>[
             Container(
               height: 200,
               width: double.infinity,
               child: HomeSlider(),
             ),
             Padding(
               padding: EdgeInsets.only(top: 14.0, left: 8.0, right: 8.0),
               child: Text(
                   AppLocalizations.of(context)
                       .translate('leatest_producrs'),
                   style: TextStyle(
                       color: Theme.of(context).accentColor,
                       fontSize: 18,
                       fontWeight: FontWeight.w700)),
             ),
             Container(
               margin: EdgeInsets.symmetric(vertical: 8.0),
               height: 200.0,
               child: Expanded(
                 child: ListView.builder(
                   shrinkWrap: true,
                   scrollDirection: Axis.horizontal,
                   itemCount: cards.length,
                   itemBuilder: (BuildContext context, int index) => Card(
                     child: InkWell(
                       child: Column(
                         children: [
                           Flexible(
                             child: Container(
                               height: double.infinity,
                               width: 120,
                               decoration: BoxDecoration(
                                   image: DecorationImage(
                                 image: NetworkImage(
                                   cards[index].productImg,
                                 ),
                                 fit: BoxFit.fitHeight,
                               )),
                             ),
                           ),
                           Container(
                             width: 150,
                             padding: EdgeInsets.all(10),
                             child: Text(cards[index].productName,
                                 style: new TextStyle(fontSize: 12),
                                 softWrap: true),
                           ),
                         ],
                       ),
                       onTap: () 
                         Fluttertoast.showToast(
                             msg: cards[index].productName,
                             toastLength: Toast.LENGTH_SHORT,
                             gravity: ToastGravity.BOTTOM,
                             timeInSecForiosWeb: 1,
                             backgroundColor: Colors.white70,
                             textColor: Colors.black,
                             fontSize: 16.0);
                       ,
                     ),
                   ),
                 ),
               ),
             ),
             Container(
               child: Padding(
                 padding: EdgeInsets.only(top: 6.0, left: 8.0, right: 8.0),
                 child: Image(
                   fit: BoxFit.cover,
                   image: AssetImage('assets/images/banner-1.jpg'),
                 ),
               ),
             ),
             Row(
               mainAxisAlignment: MainAxisAlignment.spaceBetween,
               children: <Widget>[
                 Padding(
                   padding: EdgeInsets.only(top: 8.0, left: 8.0, right: 8.0),
                   child: Text('Featured Products',
                       style: TextStyle(
                           color: Theme.of(context).accentColor,
                           fontSize: 18,
                           fontWeight: FontWeight.w700)),
                 ),
                 Padding(
                   padding: const EdgeInsets.only(
                       right: 8.0, top: 8.0, left: 8.0),
                   child: RaisedButton(
                       color: Theme.of(context).primaryColor,
                       child: Text('View All',
                           style: TextStyle(color: Colors.white)),
                       onPressed: () 
                         Navigator.pushNamed(context, '/categorise');
                       ),
                 )
               ],
             ),
             Container(
               child: GridView.count(
                 shrinkWrap: true,
                 physics: NeverScrollableScrollPhysics(),
                 crossAxisCount: 2,
                 padding:
                     EdgeInsets.only(top: 8, left: 6, right: 6, bottom: 12),
                 children: List.generate(cards.length, (index) 
                   return Container(
                     child: Card(
                       clipBehavior: Clip.antiAlias,
                       child: InkWell(
                         onTap: () 
                           print('Card tapped.');
                         ,
                         child: Column(
                           crossAxisAlignment: CrossAxisAlignment.start,
                           children: <Widget>[
                             Flexible(
                               child: Container(
                                 height: double.infinity,
                                 width: double.infinity,
                                 decoration: BoxDecoration(
                                     image: DecorationImage(
                                   image: NetworkImage(
                                     cards[index].productImg,
                                   ),
                                   fit: BoxFit.fitHeight,
                                 )),
                               ),
                             ),
                             ListTile(
                                 title: Text(
                               cards[index].productName,
                               style: TextStyle(
                                   fontWeight: FontWeight.w700,
                                   fontSize: 12),
                             )),
                           ],
                         ),
                       ),
                     ),
                   );
                 ),
               ),
             ),
             Container(
               child: Padding(
                 padding: EdgeInsets.only(
                     top: 6.0, left: 8.0, right: 8.0, bottom: 10),
                 child: Image(
                   fit: BoxFit.cover,
                   image: AssetImage('assets/images/banner-2.jpg'),
                 ),
               ),
             )
           ],
         ),
       ),
     ));


错误代码是


══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown while applying parent data.:
Incorrect use of ParentDataWidget.
The ParentDataWidget Expanded(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 Expanded widget has the wrong ancestor RenderObjectWidget. Typically,
Expanded widgets are placed directly inside Flex widgets.
The offending Expanded is currently placed inside a ConstrainedBox widget.
The ownership chain for the RenderObject that received the incompatible parent data was:
  RepaintBoundary ← NotificationListener<ScrollNotification> ← GlowingOverscrollIndicator ←
Scrollable ← ListView ← Expanded ← ConstrainedBox ← Padding ← Container ← Column ← ⋯

When the exception was thrown, this was the stack:
.
.
.
.
(elided 4 frames from class _RawReceivePortImpl, class _Timer, and dart:async-patch)
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown while applying parent data.:
Incorrect use of ParentDataWidget.

The ParentDataWidget Expanded(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 Expanded widget has the wrong ancestor RenderObjectWidget. Typically, Expanded widgets are placed directly inside Flex widgets.
The offending Expanded is currently placed inside a ConstrainedBox widget.

The ownership chain for the RenderObject that received the incompatible parent data was:
  RepaintBoundary ← NotificationListener<ScrollNotification> ← GlowingOverscrollIndicator ← Scrollable ← ListView ← Expanded ← ConstrainedBox ← Padding ← Container ← Column ← ⋯
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)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

【问题讨论】:

【参考方案1】:

Expanded 小部件必须是 Column、Row 或 Flex 的直接子级。你把它包裹在一个容器中。尝试交换 Container 和 Expanded 小部件。

【讨论】:

【参考方案2】:

您可以在下面复制粘贴运行完整代码 在您的情况下,您不需要 Expanded 因为您已经将 Container height 设置为 200 代码sn-p

Container(
        margin: EdgeInsets.symmetric(vertical: 8.0),
        height: 200.0,
        child: ListView.builder(

工作演示

完整代码

import 'package:flutter/material.dart';

void main() 
  runApp(MyApp());


class MyApp extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  


class CardItem 
  String productImg;
  String productName;

  CardItem(this.productImg, this.productName);


class MyHomePage extends StatefulWidget 
  MyHomePage(Key key, this.title) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();


class _MyHomePageState extends State<MyHomePage> 
  int _counter = 0;

  void _incrementCounter() 
    setState(() 
      _counter++;
    );
  

  List<CardItem> cards = [
    CardItem(productImg: "https://picsum.photos/250?image=9", productName: "a"),
     CardItem(
        productImg: "https://picsum.photos/250?image=10", productName: "b"),
    CardItem(
        productImg: "https://picsum.photos/250?image=11", productName: "c"),
    CardItem(
        productImg: "https://picsum.photos/250?image=12", productName: "d"),
    CardItem(
        productImg: "https://picsum.photos/250?image=13", productName: "e"),
    CardItem(
        productImg: "https://picsum.photos/250?image=14", productName: "f"),
    CardItem(
        productImg: "https://picsum.photos/250?image=15", productName: "g"),
    CardItem(
        productImg: "https://picsum.photos/250?image=16", productName: "h")
  ];

  @override
  Widget build(BuildContext context) 
    return Scaffold(
        appBar: AppBar(
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.shopping_cart),
              onPressed: () ,
            )
          ],
          backgroundColor: Colors.green,
        ),
        /* drawer: Drawer(
          child: AppDrawer(),
        ),*/
        body: SingleChildScrollView(
            child: ConstrainedBox(
              constraints: BoxConstraints(),
              child: Column(
                children: <Widget>[
                  Container(
                    height: 200,
                    width: double.infinity,
                    child: Text("HomeSlider()"),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 14.0, left: 8.0, right: 8.0),
                    child: Text(
                        'leatest_producrs',
                        style: TextStyle(
                            color: Theme.of(context).accentColor,
                            fontSize: 18,
                            fontWeight: FontWeight.w700)),
                  ),
                  Container(
                    margin: EdgeInsets.symmetric(vertical: 8.0),
                    height: 200.0,
                    child: ListView.builder(
                      shrinkWrap: true,
                      scrollDirection: Axis.horizontal,
                      itemCount: cards.length,
                      itemBuilder: (BuildContext context, int index) => Card(
                        child: InkWell(
                          child: Column(
                            children: [
                              Flexible(
                                child: Container(
                                  height: double.infinity,
                                  width: 120,
                                  decoration: BoxDecoration(
                                      image: DecorationImage(
                                        image: NetworkImage(
                                          cards[index].productImg,
                                        ),
                                        fit: BoxFit.fitHeight,
                                      )),
                                ),
                              ),
                              Container(
                                width: 150,
                                padding: EdgeInsets.all(10),
                                child: Text(cards[index].productName,
                                    style: new TextStyle(fontSize: 12),
                                    softWrap: true),
                              ),
                            ],
                          ),
                          onTap: () 

                          ,
                        ),
                      ),
                    ),
                  ),
                  Container(
                    child: Padding(
                      padding: EdgeInsets.only(top: 6.0, left: 8.0, right: 8.0),
                      child: Image(
                        fit: BoxFit.cover,
                        image: AssetImage('assets/images/banner-1.jpg'),
                      ),
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.only(top: 8.0, left: 8.0, right: 8.0),
                        child: Text('Featured Products',
                            style: TextStyle(
                                color: Theme.of(context).accentColor,
                                fontSize: 18,
                                fontWeight: FontWeight.w700)),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(
                            right: 8.0, top: 8.0, left: 8.0),
                        child: RaisedButton(
                            color: Theme.of(context).primaryColor,
                            child: Text('View All',
                                style: TextStyle(color: Colors.white)),
                            onPressed: () 
                              Navigator.pushNamed(context, '/categorise');
                            ),
                      )
                    ],
                  ),
                  Container(
                    child: GridView.count(
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      crossAxisCount: 2,
                      padding:
                      EdgeInsets.only(top: 8, left: 6, right: 6, bottom: 12),
                      children: List.generate(cards.length, (index) 
                        return Container(
                          child: Card(
                            clipBehavior: Clip.antiAlias,
                            child: InkWell(
                              onTap: () 
                                print('Card tapped.');
                              ,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Flexible(
                                    child: Container(
                                      height: double.infinity,
                                      width: double.infinity,
                                      decoration: BoxDecoration(
                                          image: DecorationImage(
                                            image: NetworkImage(
                                              cards[index].productImg,
                                            ),
                                            fit: BoxFit.fitHeight,
                                          )),
                                    ),
                                  ),
                                  ListTile(
                                      title: Text(
                                        cards[index].productName,
                                        style: TextStyle(
                                            fontWeight: FontWeight.w700,
                                            fontSize: 12),
                                      )),
                                ],
                              ),
                            ),
                          ),
                        );
                      ),
                    ),
                  ),
                  Container(
                    child: Padding(
                      padding: EdgeInsets.only(
                          top: 6.0, left: 8.0, right: 8.0, bottom: 10),
                      child: Image(
                        fit: BoxFit.cover,
                        image: AssetImage('assets/images/banner-2.jpg'),
                      ),
                    ),
                  )
                ],
              ),
            ),
          )
        );
  

【讨论】:

以上是关于- 如何解决:ParentDataWidget 使用不正确?的主要内容,如果未能解决你的问题,请参考以下文章

错误在我的应用程序中不正确使用 ParentDataWidget

如何修复这个特定的“不正确使用 ParentDataWidget”。飞镖

ParentDataWidget 的错误使用

添加容器颜色时出错:ParentDataWidget 的使用不正确

在垂直列表视图中添加水平列表视图时不正确使用 ParentDataWidget

谷歌地图标记(当前位置)使应用程序崩溃,如何解决?