断言失败:第 6075 行 pos 12:'child == _child':不正确

Posted

技术标签:

【中文标题】断言失败:第 6075 行 pos 12:\'child == _child\':不正确【英文标题】:Failed assertion: line 6075 pos 12: 'child == _child': is not true断言失败:第 6075 行 pos 12:'child == _child':不正确 【发布时间】:2021-11-02 17:08:01 【问题描述】:

我是 Flutter 的新手,尝试向应用程序显示最近的用户/供应商。教程中的人做得很顺利,但我遇到了很多错误。我正在编写与他在教程中编写的完全相同的代码。

断言失败:第 6075 行第 12 行:'child == _child':不正确。 在小部件树中检测到重复的 GlobalKey。 RenderShrinkWrappingViewport 需要 RenderSliv​​er 类型的子级,但收到了 RenderFlex 类型的子级。

这是我的代码。

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:paginate_firestore/bloc/pagination_listeners.dart';
import 'package:paginate_firestore/paginate_firestore.dart';
import 'package:phatafut/providers/store_provider.dart';
import 'package:phatafut/services/store_services.dart';
import 'package:provider/provider.dart';
import '../constants.dart';

class NearestStore extends StatefulWidget 
  static const id = 'nearest-store-screen';
  const NearestStore(key) : super(key: key);

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


class _NearestStoreState extends State<NearestStore> 
  StoreServices _storeServices = StoreServices();
  PaginateRefreshedChangeListener refreshedChangeListener = PaginateRefreshedChangeListener();

  @override
  Widget build(BuildContext context) 
    final _storeData = Provider.of<StoreProvider>(context);
    _storeData.getUserLocationData(context);

    String getDistance(location)
      var distance = Geolocator.distanceBetween(
        _storeData.userLatitude, _storeData.userLongitude, location.latitude, location.longitude,
      );
      var distanceInKM = distance/1000;
      return distanceInKM.toStringAsFixed(2);
    

    return Container(
      child: StreamBuilder<QuerySnapshot>(
        stream: _storeServices.getnearestStore(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot>snapShot)
          if(!snapShot.hasData)
            return CircularProgressIndicator();
          List shopDistance = [];
          for(int i=0 ; i<=snapShot.data.docs.length-1; i++)
            var distance = Geolocator.distanceBetween(
                _storeData.userLatitude, _storeData.userLongitude,
                snapShot.data.docs[i]['location'].latitude,
                snapShot.data.docs[i]['location'].longitude
            );
            var distanceInKM = distance/1000;
            shopDistance.add(distanceInKM);
          
          shopDistance.sort();
          if(shopDistance[0]>1)
            return Container();
          
          return Padding(padding: EdgeInsets.all(8),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              RefreshIndicator(
                child: PaginateFirestore(
                  bottomLoader: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Theme.of(context).primaryColor),
                  ),
                  header: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(
                          left: 8,right: 8,top: 20,),
                        child: Text('All Nearby Stores',
                          style: TextStyle(fontWeight: FontWeight.w700,
                            fontSize: 21,
                          ),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(
                          left: 8,right: 8,top: 20,),
                        child: Text('Find out quality products Nearby You',
                          style: TextStyle(
                              fontSize: 21,
                              color: Colors.blueGrey
                          ),
                        ),
                      ),
                    ],
                  ),
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  itemBuilderType: PaginateBuilderType.listView,
                  itemBuilder: (index, context, document)=>
                  Padding(
                    padding: const EdgeInsets.all(4),
                    child: Container(
                      width: MediaQuery.of(context).size.width,
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          SizedBox(
                            width: 100,
                            height: 110,
                            child: Card(
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(4),
                                child: Image.network(document['imageUrl'],fit:BoxFit.cover),
                              ),
                            ),
                          ),
                          SizedBox(width: 10,),
                          Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Container(
                                child: Text(document['shopName'],
                                  style: TextStyle(
                                    fontSize: 14,
                                    fontWeight: FontWeight.bold,
                                  ),
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                              SizedBox(height: 3,),
                              Text(document['dialog'],
                                style: KShopCardStyle,
                              ),
                              SizedBox(height: 3,),
                              Container(
                                width: MediaQuery.of(context).size.width-250,
                                child: Text(document['address'],
                                  overflow: TextOverflow.ellipsis,
                                  style: KShopCardStyle,
                                ),
                              ),
                              SizedBox(height: 3,),
                              Text('$getDistance(document['location'])KM',
                                overflow: TextOverflow.ellipsis,
                                style: KShopCardStyle,
                              ),
                              SizedBox(height: 3,),
                              Row(
                                children: [
                                  Icon(Icons.star,
                                    size: 12,
                                    color: Colors.blueGrey,
                                  ),
                                  SizedBox(width: 4,),
                                  Text('4.0',
                                    style: KShopCardStyle,
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                  query: FirebaseFirestore.instance
                      .collection('vendors')
                      .where('accVerified', isEqualTo: true)
                      .where('isTopPicked',isEqualTo: true)
                      .orderBy('shopName'),
                  listeners: [
                    refreshedChangeListener,
                  ],
                  footer: Padding(
                    padding: const EdgeInsets.only(top: 30,),
                    child: Container(
                      child: Stack(
                        children: [
                          Center(
                            child: Text('**That\s all folks**',
                              style: TextStyle(
                                color: Colors.blueGrey,
                              ),
                            ),
                          ),
                          Image.asset('images/city.png'),
                          Positioned(
                            right: 10.0,
                            top: 80,
                            child: Container(
                              width: 100,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text('Made by : ',
                                    style: TextStyle(
                                      color: Colors.black12,
                                    ),
                                  ),
                                  Text('Adeel',
                                    style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      color: Colors.black,
                                      letterSpacing: 2,
                                      fontFamily: 'Poppins-Bold',
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                  onRefresh: ()async
                  refreshedChangeListener.refreshed = true;
                ,
              ),
            ],
          ),
          );
        ,
      ),
      );
  

这里是错误日志

======== Exception caught by widgets library =======================================================
The following assertion was thrown building RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#1b72f](state: RawGestureDetectorState#3b342(gestures: <none>, behavior: opaque)):
A RenderShrinkWrappingViewport expected a child of type RenderSliver but received a child of type RenderFlex.

RenderObjects expect specific types of children because they coordinate with their children during layout and paint. For example, a RenderSliver cannot be the child of a RenderBox because a RenderSliver does not understand the RenderBox layout protocol.
The RenderShrinkWrappingViewport that expected a RenderSliver child was created by: ShrinkWrappingViewport ← IgnorePointer-[GlobalKey#8e459] ← Semantics ← Listener ← _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#1b72f] ← Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#ad7bb] ← RepaintBoundary ← CustomPaint ← RepaintBoundary ← ⋯
The RenderFlex that did not match the expected child type was created by: Column ← ShrinkWrappingViewport ← IgnorePointer-[GlobalKey#8e459] ← Semantics ← Listener ← _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#1b72f] ← Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#ad7bb] ← RepaintBoundary ← CustomPaint ← ⋯
The relevant error-causing widget was: 
  PaginateFirestore file:///C:/Users/The%20Cubix/StudioProjects/project_phatafut/phatafut/lib/widgets/neareststore.dart:220:24
When the exception was thrown, this was the stack: 
#0      ContainerRenderObjectMixin.debugValidateChild.<anonymous closure> (package:flutter/src/rendering/object.dart:3129:9)
#1      ContainerRenderObjectMixin.debugValidateChild (package:flutter/src/rendering/object.dart:3156:6)
#2      MultiChildRenderObjectElement.insertRenderObjectChild (package:flutter/src/widgets/framework.dart:6160:25)
#3      RenderObjectElement.attachRenderObject (package:flutter/src/widgets/framework.dart:5758:35)
#4      RenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5440:5)
...
====================================================================================================

======== Exception caught by widgets library =======================================================
The following assertion was thrown building RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#1b72f](state: RawGestureDetectorState#3b342(gestures: <none>, behavior: opaque)):
'package:flutter/src/widgets/framework.dart': Failed assertion: line 6075 pos 12: 'child == _child': is not true.


Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
  https://github.com/flutter/flutter/issues/new?template=2_bug.md

The relevant error-causing widget was: 
  PaginateFirestore file:///C:/Users/The%20Cubix/StudioProjects/project_phatafut/phatafut/lib/widgets/neareststore.dart:220:24
When the exception was thrown, this was the stack: 
#2      SingleChildRenderObjectElement.forgetChild (package:flutter/src/widgets/framework.dart:6075:12)
#3      Element._retakeInactiveElement (package:flutter/src/widgets/framework.dart:3563:14)
...     Normal element mounting (10 frames)
#13     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3611:14)
#14     Element.updateChild (package:flutter/src/widgets/framework.dart:3360:20)
...
====================================================================================================

======== Exception caught by widgets library =======================================================
The following assertion was thrown while finalizing the widget tree:
Duplicate GlobalKey detected in widget tree.

The following GlobalKey was specified multiple times in the widget tree. This will lead to parts of the widget tree being truncated unexpectedly, because the second time a key is seen, the previous instance is moved to the new location. The key was:
- [GlobalKey#8e459]
This was determined by noticing that after the widget with the above global key was moved out of its previous parent, that previous parent never updated during this frame, meaning that it either did not update at all or updated before the widget was moved, in either case implying that it still thinks that it should have a child with that global key.
The specific parent that did not update after having one or more children forcibly removed due to GlobalKey reparenting is:
- Semantics(container: false, properties: SemanticsProperties, label: null, value: null, hint: null, hintOverrides: null, renderObject: RenderSemanticsAnnotations#2d00d NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE DETACHED)
A GlobalKey can only be specified on one widget at a time in the widget tree.
When the exception was thrown, this was the stack: 
#0      BuildOwner.finalizeTree.<anonymous closure> (package:flutter/src/widgets/framework.dart:2900:15)
#1      BuildOwner.finalizeTree (package:flutter/src/widgets/framework.dart:2925:8)
#2      WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:877:19)
#3      RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:328:5)
#4      SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15)
...
====================================================================================================

【问题讨论】:

***.com/questions/49371221/… @gtxtreme 感谢您的回复。我的代码中没有使用任何globalKey。甚至不做导航。请查看代码。 一个原因可能是由于某种原因您的小部件的约束为负数,例如如果 sizedbox/container 高度或宽度为负数。 @AsfarAli 感谢您的宝贵回复,但我想通了。 【参考方案1】:

RenderShrinkWrappingViewport 需要一个 RenderSliv​​er 类型的子项 但收到了一个 RenderFlex 类型的子节点。

headerfooter 属性应该是 Slivers(没有文档参考,但 example 和 implementation 显示了这一点)所以为了使用非 sliver 小部件,你可以用SliverToBoxAdapter 是“包含单个盒子小部件的条子。”

header 代码更新为:

header: SliverToBoxAdapter(
  child: Column(
    ...
  ),
),

并将footer 代码更新为:

footer: SliverToBoxAdapter(
  child: Padding(
    ...
  )
),

【讨论】:

【参考方案2】:

标题:SliverToBoxAdapter( 孩子:填充( 页脚:SliverToBoxAdapter( 孩子:填充(

【讨论】:

正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center。 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。

以上是关于断言失败:第 6075 行 pos 12:'child == _child':不正确的主要内容,如果未能解决你的问题,请参考以下文章

断言失败:第 551 行 pos 12:'child.hasSize':不正确

断言行 5120 pos 12 失败:'child = _child' 不正确

断言失败:第 125 行第 12 行:'assertMidButtonStyles(navBarStyle, items!.length)'

断言失败:第 22 行 pos 14: 'url != null': is not true

Flutter 错误 - 断言失败:第 213 行 pos 15:'data != null':在从 firestore 获取数据时不正确

Flutter - 断言失败:第 61 行第 12 行:'_route == ModalRoute.of(context)':不正确