简体   繁体   中英

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,
    );
  }
}

I solved my Question.

You can't name the coustom 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,
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM