“Multiple widgets used the same GlobalKey” despite generation of unique keys

I have a screen where the user is shown multiple recommendations or in this case just items with TextFormFields. Those items are stacked above each other using the package SwipableStack. For each item the user can swipe right to accept or swipe left to dismiss (it’s comparable to dating apps like Tinder). When he wants to accept the item, the input of the TextFormField is validated.

Issue:
The initial build works perfectly fine. After I accept the first item, it is removed as it should. But after that, the following error occurs multiple times when rebuilding the screen:

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

The key [LabeledGlobalKey<FormState>#9dc26] was used by multiple widgets. The parents of those widgets were:
- Padding(padding: EdgeInsets.all(15.0), dependencies: [Directionality], renderObject: RenderPadding#386b3)
- Padding(padding: EdgeInsets.all(15.0), dependencies: [Directionality], renderObject: RenderPadding#0a341)
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._debugVerifyGlobalKeyReservation.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:flutter/src/widgets/framework.dart:3205:13)
#1      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:633:13)
#2      BuildOwner._debugVerifyGlobalKeyReservation.<anonymous closure>.<anonymous closure> (package:flutter/src/widgets/framework.dart:3149:20)
#3      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:633:13)
#4      BuildOwner._debugVerifyGlobalKeyReservation.<anonymous closure> (package:flutter/src/widgets/framework.dart:3144:36)
#5      BuildOwner._debugVerifyGlobalKeyReservation (package:flutter/src/widgets/framework.dart:3213:6)
#6      BuildOwner.finalizeTree.<anonymous closure> (package:flutter/src/widgets/framework.dart:3267:11)
#7      BuildOwner.finalizeTree (package:flutter/src/widgets/framework.dart:3342:8)
#8      WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:1169:19)
#9      RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:468:5)
#10     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1397:15)
#11     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1318:9)
#12     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:1176:5)
#13     _invoke (dart:ui/hooks.dart:312:13)
#14     PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:419:5)
#15     _drawFrame (dart:ui/hooks.dart:283:31)
====================================================================================================

I suppose that there are still old instances somewhere in the Widget tree that lead to those issues. But I can not figure it out how this can be solved.

Here’s the current code:

import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:investiquo/1-general/services/formatter.dart';
import 'package:investiquo/1-general/templates/styling.dart';
import 'package:swipable_stack/swipable_stack.dart';

class RecommendationsScreen extends StatefulWidget {
  /// Controller is irrelevant for this instance
  static late SwipableStackController controller;

  const RecommendationsScreen({
    super.key,
  });

  @override
  State<RecommendationsScreen> createState() => _RecommendationsScreenState();
}

class _RecommendationsScreenState extends State<RecommendationsScreen> {
  final int swipeActionDuration = 750;
  int noOfRemovedItems = 0;
  List<Widget>? recommendationTiles;
  List<GlobalKey<FormState>> formKeys = [];

  List<Map<String, dynamic>> items = [
    {
      'label': 'ABC',
    },
    {
      'label': 'DEF',
    },
    {
      'label': 'GHI',
    },
    {
      'label': 'JKL',
    },
  ];

  void updateFormKeys() {
    /// Update no. of formKeys if there are either too many or not enough for each item
    if (formKeys.length != items.length) {
      formKeys = List.generate(
        items.length,
        (_) => GlobalKey<FormState>(),
      );
    }
  }

  List<Widget> currentRecommendationWidgets({
    required AppLocalizations t,
  }) {
    List<Widget> recommendationItems = [];

    updateFormKeys();

    for (int i = 0; i < items.length; i++) {
      recommendationItems.add(
        Container(
          color: kTileBackgroundColor,
          padding: EdgeInsets.all(kDefaultScreenPaddingAllSides),
          child: Form(
            key: formKeys[i],
            child: TextFormField(
              decoration: InputDecoration(
                label: Text(items[i]['label']),
              ),
              validator: (String? value) {
                final String adjustedValue = removeAllSeparators(
                  value,
                  Localizations.localeOf(context).toLanguageTag(),
                );

                if (adjustedValue.isEmpty) {
                  return 'Please enter a value';
                }

                return null;
              },
            ),
          ),
        ),
      );
    }

    return recommendationItems;
  }

  @override
  void initState() {
    formKeys = List.generate(
      items.length,
      (_) => GlobalKey<FormState>(),
    );

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final AppLocalizations t = AppLocalizations.of(context)!;

    recommendationTiles ??= currentRecommendationWidgets(
      t: t,
    );

    return Container(
      margin: const EdgeInsets.symmetric(vertical: kDefaultScreenPaddingAllSides),
      child: Stack(
        children: [
          items.isNotEmpty
              ? Positioned.fill(
                  child: SwipableStack(
                    allowVerticalSwipe: false,
                    stackClipBehaviour: Clip.none,
                    overlayBuilder: (context, properties) {
                      /// Overlay that indicates to the user if he is about to accept or dismiss the current item
                      final opacity = min(properties.swipeProgress, 1.0);
                      final isRight = properties.direction == SwipeDirection.right;

                      return properties.swipeProgress >= 0.15
                          ? Opacity(
                              opacity: opacity,
                              child: Stack(
                                children: [
                                  isRight
                                      ? Positioned(
                                          left: 0,
                                          top: MediaQuery.of(context).size.height / 4,
                                          child: Container(
                                            padding: const EdgeInsets.all(kDefaultScreenPaddingAllSides),
                                            decoration: BoxDecoration(
                                              color: Colors.white,
                                              border: Border.all(
                                                color: kTextInputOutline,
                                                width: 1.0,
                                              ),
                                              borderRadius: BorderRadius.circular(0.0),
                                            ),
                                            child: Text(
                                              t.recommendationGeneralImplementLabel,
                                              style: const TextStyle(
                                                fontSize: kDefaultHeaderSize,
                                                color: kSuccessColor,
                                              ),
                                            ),
                                          ),
                                        )
                                      : Positioned(
                                          right: 0,
                                          top: MediaQuery.of(context).size.height / 4,
                                          child: Container(
                                            padding: const EdgeInsets.all(kDefaultScreenPaddingAllSides),
                                            decoration: BoxDecoration(
                                              color: Colors.white,
                                              border: Border.all(
                                                color: kTextInputOutline,
                                                width: 1.0,
                                              ),
                                              borderRadius: BorderRadius.circular(0.0),
                                            ),
                                            child: Text(
                                              t.recommendationGeneralIgnoreLabel,
                                              style: const TextStyle(
                                                fontSize: kDefaultHeaderSize,
                                                color: kFailureColor,
                                              ),
                                            ),
                                          ),
                                        ),
                                ],
                              ),
                            )
                          : Container();
                    },
                    horizontalSwipeThreshold: 0.8,
                    onWillMoveNext: (i, direction) {
                      /// If the user wants to accept the item the TextFormField needs to be validated. Proceed only if it returns true
                      bool isLeft = direction == SwipeDirection.left;
                      bool isRight = direction == SwipeDirection.right;
                      bool isValidated = formKeys[0].currentState?.validate() ?? false;

                      return isLeft || (isRight && isValidated);
                    },
                    onSwipeCompleted: (i, direction) async {
                      /// To simplify the matter we only want to print to the console depending on the chosen action
                      if (direction == SwipeDirection.right) {
                        print('Accepted');
                      } else if (direction == SwipeDirection.left) {
                        print('Declined');
                      }

                      /// After the swipe was completed we want to remove the top card so that instead of for example label "ABC" now "DEF" is shown
                      items.removeAt(0);

                      noOfRemovedItems += 1;

                      /// Update recommendationTile according to the new number of items
                      setState(() {
                        recommendationTiles = currentRecommendationWidgets(
                          t: t,
                        );
                      });
                    },
                    builder: (context, properties) {
                      final int currentIndex = (properties.index - noOfRemovedItems).clamp(
                        0,
                        recommendationTiles!.length - 1,
                      );

                      return recommendationTiles![currentIndex];
                    },
                  ),
                )
              : Container(),
        ],
      ),
    );
  }
}

Thanks a lot for any help! Really appreciate it.

All the best,
Alex

Expectation:
The user can go through the whole stack of items. For each item the respective validator is triggered when the user swipes right.

Actual result:
The first swipe works just fine. After that, when items[1] is supposed to load or to take over the top of the stack, the “Multiple widgets used the same GlobalKey” error occurs.

I have tried different locations of the Form widget and to generate new GlobalKeys on each rebuild.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật