首页 > 解决方案 > 断言失败:第 6075 行 pos 12:'child == _child':不正确

问题描述

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

这是我的代码。

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)
...
====================================================================================================

标签: androidflutterdartflutter-layout

解决方案


RenderShrinkWrappingViewport 需要 RenderSliv​​er 类型的子级,但接收到 RenderFlex 类型的子级。

和属性应该是 Slivers(没有文档参考,但header示例实现显示了这一点),因此为了使用非 sliver 小部件,您可以使用SliverToBoxAdapter包装它们,这是“包含单个框小部件的 sliver。 "footer

header将代码更新为:

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

并将代码更新footer为:

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

推荐阅读