dart 多个微件使用同一GlobalKey

cl25kdpy  于 2023-02-06  发布在  其他
关注(0)|答案(8)|浏览(164)

我使用Flutter。我有一个简单的应用程序,有3个标签页。每个标签页都有一个RefreshIndicator和一个ListView。行是用另一个方法构建的。代码如下:

@override
 Widget build(BuildContext context) {
    final GlobalKey<RefreshIndicatorState> _RIKey1 = new GlobalKey<RefreshIndicatorState>();
    final GlobalKey<RefreshIndicatorState> _RIKey2 = new GlobalKey<RefreshIndicatorState>();
    final GlobalKey<RefreshIndicatorState> _RIKey3 = new GlobalKey<RefreshIndicatorState>();

    debugPrint(_RIKey1.toString());
    debugPrint(_RIKey2.toString());
    debugPrint(_RIKey3.toString());
    return new Scaffold(
      body: new DefaultTabController(
        length: 3,
        child: new Scaffold(
          appBar: new AppBar(
            bottom: new TabBar(
              tabs: [
                new Tab(icon: new Icon(Icons.view_list)),
                new Tab(icon: new Icon(Icons.hotel)),
                new Tab(icon: new Icon(Icons.assessment)),
              ],
            ),
            title: new Text('Data'),
          ),
          body: new TabBarView(
            children: [
              new RefreshIndicator(
                key: _RIKey1,
                onRefresh: _actualizoData,
                child: new ListView.builder(
                    padding: new EdgeInsets.only(top: 5.0),
                    itemCount: linea_reservas.length * 2,
                    itemBuilder: (BuildContext context, int position) {
                      if (position.isOdd) return new Divider();
                      final index = position ~/ 2;
                      return _buildRow(index);
                    }),
              ),
              new RefreshIndicator(
                key: _RIKey2,
                onRefresh: _actualizoData,
                child: new ListView.builder(
                    padding: new EdgeInsets.only(top: 8.0),
                    itemCount: linea_inouthouse.length * 2,
                    itemBuilder: (BuildContext context, int position) {
                      if (position.isOdd) return new Divider();
                      final index = position ~/ 2;
                      return _buildRowInOutHouse(index);
                    }),
              ),
              new RefreshIndicator(
                key: _RIKey3,
                onRefresh: _actualizoData,
                child: new ListView.builder(
                    padding: new EdgeInsets.only(top: 5.0),
                    itemCount: linea_ocupacion.length * 2,
                    itemBuilder: (BuildContext context, int position) {
                      if (position.isOdd) return new Divider();
                      final index = position ~/ 2;
                      return _buildRowOcupacion(index);
                    }),
              ),
            ],
          ),
        ),
      ),
    );
  }

我添加了debugPrints,输出为6行,而不是3行。

I/flutter ( 5252): [LabeledGlobalKey<RefreshIndicatorState>#4d76c]
I/flutter ( 5252): [LabeledGlobalKey<RefreshIndicatorState>#59b9e]
I/flutter ( 5252): [LabeledGlobalKey<RefreshIndicatorState>#2c88b]
I/flutter ( 5252): [LabeledGlobalKey<RefreshIndicatorState>#7bd42]
I/flutter ( 5252): [LabeledGlobalKey<RefreshIndicatorState>#1c984]
I/flutter ( 5252): [LabeledGlobalKey<RefreshIndicatorState>#dbe20]

应用程序工作正常,但在更改选项卡几次后,它崩溃并显示以下错误:

I/flutter ( 5252): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 5252): The following assertion was thrown building NotificationListener<KeepAliveNotification>:
I/flutter ( 5252): Multiple widgets used the same GlobalKey.
I/flutter ( 5252): The key [LabeledGlobalKey<RefreshIndicatorState>#7bd42] was used by multiple widgets. The parents of
I/flutter ( 5252): those widgets were:
I/flutter ( 5252): - RepaintBoundary-[<[LabeledGlobalKey<RefreshIndicatorState>#7bd42]>](renderObject:
I/flutter ( 5252):   RenderRepaintBoundary#60a4a DETACHED)
I/flutter ( 5252): - RepaintBoundary-[<[LabeledGlobalKey<RefreshIndicatorState>#7bd42]>](renderObject:
I/flutter ( 5252):   RenderRepaintBoundary#c8cdb NEEDS-LAYOUT NEEDS-PAINT)
I/flutter ( 5252): A GlobalKey can only be specified on one widget at a time in the widget tree.

键是在Build方法中生成的,因此,我不明白为什么会出现Multiple widgets used the same GlobalKey错误
为什么密钥会再次生成,为什么它不是唯一的?我不是在谈论一千个意图,错误出现后,在标签之间切换4或5次。谢谢你的任何帮助。

oxf4rvwz

oxf4rvwz1#

你能“手工”创建你的密钥并使用静态/常量值吗?例如......

import 'package:flutter/widgets.dart';

class RIKeys {
  static final riKey1 = const Key('__RIKEY1__');
  static final riKey2 = const Key('__RIKEY2__');
  static final riKey3 = const Key('__RIKEY3__');
}

然后在...

body: new TabBarView(
            children: [
              new RefreshIndicator(new RefreshIndicator(
// Use the Manual Static Value instead ...
                key: RIKeys.riKey1,
                onRefresh: _actualizoData,
                child: new ListView.builder(
                    padding: new EdgeInsets.only(top: 5.0),
                    itemCount: linea_reservas.length * 2,
                    itemBuilder: (BuildContext context, int position) {
                      if (position.isOdd) return new Divider();
                      final index = position ~/ 2;
                      return _buildRow(index);
                    }),
              ),

我在类似的情况下做过这件事,取得了一些成功...尤其是用redux或其他类似的模式...

sbtkgmzw

sbtkgmzw2#

我想创建一个表单键列表。
只需将GlobalKey更改为GlobalObjectKey
就像下面。

final List<GlobalObjectKey<FormState>> formKeyList = List.generate(10, (index) => GlobalObjectKey<FormState>(index));
iecba09b

iecba09b3#

对于需要继续使用GlobalKey的用户:

import 'package:flutter/widgets.dart';

class JosKeys {
  static final josKeys1 = GlobalKey();
  static final josKeys2 = GlobalKey();
}

使用如下:

[
    CoachTutorialModel(
      ids: "post",
      globalKeys: JosKeys.josKeys1,
      icons: Icon(
        Icons.message,
        color: Colors.white,
        size: 90,
      ),
      ...
    ),

   CoachTutorialModel(
      ids: "post2",
      globalKeys: JosKeys.josKeys2,
      icons: Icon(
        Icons.message,
        color: Colors.white,
        size: 90,
      ),
      ...
    ),
]
f87krz0w

f87krz0w4#

在我的例子中,我在一个方法中添加了一个键到一个小部件,该方法在多个地方被调用,代码不是我的,所以需要一段时间来调试,只是将其留在这里,也许它会帮助一些人。

busg9geu

busg9geu5#

由于循环依赖,我在flutter项目中遇到了这个问题。请检查Widget A是否导入了Widget B,以及Widget B是否导入了Windget A

vpfxa7rd

vpfxa7rd6#

我使用了一个 Package 容器小部件的自定义小部件。我需要将key从自定义小部件传递到容器,并且我在 Package 器构造函数中使用了参数key。遇到了相同的问题。我的修复方法是避免在 Package 器构造函数中使用单词key,将其更改为refKey,错误消失。

u1ehiz5o

u1ehiz5o7#

我使用的是riverpodgorouter,我的导航键是这样的:

final navKeyProv = Provider.autoDispose(
  (_) => GlobalKey<NavigatorState>(),
);

从提供程序中删除自动处理为我修复了它:

final navKeyProv = Provider(
  (_) => GlobalKey<NavigatorState>(),
);
azpvetkf

azpvetkf8#

和上面的@babernethy一样,你可以拥有

import 'package:flutter/widgets.dart';

class JosKeys {
  static final josKeys1 = const Key('__JosKey1__');
  static final josKeys2 = const Key('__JosKey2__');
}

然后对其中一个全局密钥执行此操作,确保每个全局密钥都有不同的JosKeys.josKeys{number}

GlobalKey _globalKey = JosKeys.josKeys1;

相关问题