Flutter开发 - Multiple widgets used the same GlobalKey.

1,474 阅读1分钟

最近通过sentry解决异常的时候发现了一个报错:

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown while finalizing the widget tree:
Multiple widgets used the same GlobalKey.

The key [GlobalKey#4c84a] was used by multiple widgets. The parents of those widgets were different widgets that both had the following description:
  DefaultTextStyle(debugLabel: ((englishLike body1 2014).merge((blackCupertino bodyText2).merge(unknown))).merge(lerp(unknown ⎯0.0→ unknown)), inherit: false, color: Color(0xffa1a6aa), family: .SF UI Text, size: 12.0, weight: 300, baseline: alphabetic, decoration: TextDecoration.none, softWrap: wrapping at box width, overflow: clip)
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      GlobalKey._debugVerifyGlobalKeyReservation.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:flutter/src/widgets/framework.dart:253:13)
#1      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
#2      GlobalKey._debugVerifyGlobalKeyReservation.<anonymous closure>.<anonymous closure> (package:flutter/src/widgets/framework.dart:200:20)
#3      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
#4      GlobalKey._debugVerifyGlobalKeyReservation.<anonymous closure> (package:flutter/src/widgets/framework.dart:196:26)
...

看到上面这个异常后真的是很懵逼,还看不到具体的报错内容,了解后才意识到GlobalKey这玩意真不能乱用啊!

出现这个问题的原因是因为在同一时间有两个widget使用了同一个GlobalKey,这种用法是绝对要禁止的,提醒小伙伴在使用的过程中一定要切记哦。

如果你真的不小心出了这个问题,又不知道怎么解决,教你一招,在报错的文件那里打上断点,然后错误出现在断点处的时候,根据flutter调用的树结构可以查看到具体的调用,博主就是通过framework中打断点最终确定的逻辑位置。