首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >'child == _child':不正确,在小部件树中检测到重复的GlobalKey

'child == _child':不正确,在小部件树中检测到重复的GlobalKey
EN

Stack Overflow用户
提问于 2021-06-16 08:15:56
回答 1查看 450关注 0票数 1

当我呈现一个子组件时,会得到这个错误。

  • Failed断言:第6075行pos 12:'child == _ child ':小部件tree.
  • A RenderShrinkWrappingViewport中没有检测到RenderFlex.

GlobalKey,而是接收到了RenderFlex.类型的子级

我的密码在这里.

代码语言:javascript
复制
// @dart=2.9

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

class NearByStore extends StatefulWidget {


  @override
  _NearByStoreState createState() => _NearByStoreState();
}

class _NearByStoreState extends State<NearByStore> {
  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.getTopPickedStore(), // will change it soon
        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(); // this will sort with nearest distance. if nearest distance is more than 10, that means no shop near by;
          if (shopDistance[0] > 10) {
            return Container(
              child: Stack(
                children: [
                  Center(
                    child: Text('***That all folks***',
                      style: TextStyle(color: Colors.grey),),
                  ),
                  Image.asset(
                      'images/city.png', color: Colors.black12),
                  Positioned(
                    right: 10.0,
                    top: 80,
                    child: Container(
                      width: 100,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('Made by : ', style: TextStyle(
                              color: Colors.black54
                          ),),
                          Text('VOID TECHNOLOGY', style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontFamily: 'Anton',
                              letterSpacing: 2,
                              color: Colors.grey
                          ),)
                        ],

                      ),
                    ),
                  )

                ],
              ),
            );
          }
          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.w900,
                                fontSize: 18
                            ),),
                        ),

                        Padding(
                          padding: const EdgeInsets.only(
                              left: 8, right: 8, bottom: 10
                          ),
                          child: Text('Findout quality products near you',
                            style: TextStyle(
                                fontSize: 12, color: Colors.grey
                            ),),
                        ),
                      ],
                    ),
                    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: kStoreCardStyle,),
                                    SizedBox(
                                      height: 3,
                                    ),
                                    Container(
                                      width: MediaQuery
                                          .of(context)
                                          .size
                                          .width - 250,
                                      child: Text(document['address'],
                                        overflow: TextOverflow.ellipsis,
                                        style: kStoreCardStyle,
                                      ),
                                    ),
                                    SizedBox(
                                      height: 3,
                                    ),
                                    Text(
                                      '${getDistance(document['location'])}Km',
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                    SizedBox(
                                      height: 3,
                                    ),
                                    Row(
                                      children: [
                                        Icon(
                                          Icons.star,
                                          size: 12,
                                          color: Colors.grey,
                                        ),
                                        SizedBox(
                                          width: 4,
                                        ),
                                        Text('3.2', style: kStoreCardStyle,)
                                      ],
                                    )

                                  ],
                                )

                              ],
                            ),
                          ),
                        ),
                    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 all folks***',
                                style: TextStyle(color: Colors.grey),),
                            ),
                            Image.asset(
                                'images/city.png', color: Colors.black12),
                            Positioned(
                              right: 10.0,
                              top: 80,
                              child: Container(
                                width: 100,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text('Made by : ', style: TextStyle(
                                        color: Colors.black54
                                    ),),
                                    Text('VOID TECHNOLOGY', style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        fontFamily: 'Anton',
                                        letterSpacing: 2,
                                        color: Colors.grey
                                    ),)
                                  ],

                                ),
                              ),
                            )

                          ],
                        ),
                      ),
                    ),

                  ),

                  onRefresh: () async {
                    refreshedChangeListener.refreshed = true;
                  },
                )
              ],

            ),
          );
        },
      ),
    );
  }
}

代码语言:javascript
复制
    ======== Exception caught by widgets library =======================================================
The following assertion was thrown building RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#a5a30](state: RawGestureDetectorState#b8caf(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:///E:/Flutter%20Main/flutter_project/lib/widgets/near_by_store.dart:99:26
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#4acc7]
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#faf5c 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      SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15)
#4      SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1082:9)
...
====================================================================================================
EN

回答 1

Stack Overflow用户

发布于 2021-09-05 05:01:25

headerfooter属性预计将是条条。因此,为了使用非条形小部件,可以用SliverToBoxAdapter包装它们,这是“一个包含单个方框小部件的条”。尝试这样做。Header代码更新到:

代码语言:javascript
复制
header: SliverToBoxAdapter(
  child: Column(
    ...
  ),
),

并将footer代码更新为:

代码语言:javascript
复制
footer: SliverToBoxAdapter(
  child: Padding(
    ...
  )
),
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67998846

复制
相关文章

相似问题

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