Search code examples
flutterkeyflutter-animatedlist

Animated List Multiple widgets used the same GlobalKey


I'm trying to use a GlobalKey for an AnimatedList, so I create an animation. But regardless where I declare the Globalkey (Inside StatelessWidget, Global, static in class), I always get the duplicated Key error. What am I doing wrong?

import 'package:flutter/material.dart';
void main() {
  runApp(MaterialApp(
    title: 'Navigation Basics',
    home: Scaffold(body: FirstRoute()),
  ));
}

class Keys {
  static GlobalKey<AnimatedListState> favoriteDrink =
      GlobalKey<AnimatedListState>(debugLabel: "TestKey");
}

class FirstRoute extends StatelessWidget {
  final List<String> texte = [
    "Hello",
    "Hello1",
    "Hello2",
    "Hello3",
    "Hello4",
    "Hello5"
  ];
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Center(
          child: CustomListview(
        texts: texte,
        key: Keys.favoriteDrink,
      )),
    );
  }
}

class CustomListview extends StatelessWidget {
  final List<String> texts;
  final GlobalKey<AnimatedListState> key;
  CustomListview({this.texts, this.key});

  @override
  Widget build(BuildContext context) {
    return AnimatedList(
      key: key,
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      scrollDirection: Axis.vertical,
      itemBuilder: (context, index, animation) {
        return Text(
          texts[index],
          textAlign: TextAlign.center,
        );
      },
      initialItemCount: texts.length,
    );
  }
}

Solution

  • I solved my question.

    You can't name the custom key "key". This will lead to problems.

    If you rename it to something like "customKey" it will work.

    class CustomListview extends StatelessWidget {
      final List<String> texts;
      final GlobalKey<AnimatedListState> customKey; //<--- Change this
      CustomListview({this.texts, this.customKey});
    
      @override
      Widget build(BuildContext context) {
        return AnimatedList(
          key: customKey,
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          scrollDirection: Axis.vertical,
          itemBuilder: (context, index, animation) {
            return Text(
              texts[index],
              textAlign: TextAlign.center,
            );
          },
          initialItemCount: texts.length,
        );
      }
    }