首页 > 解决方案 > 动画列表多个小部件使用相同的 GlobalKey

问题描述

我正在尝试将 GlobalKey 用于 AnimatedList,因此我创建了一个动画。但无论我在哪里声明 Globalkey(在 StatelessWidget 内部、全局、静态类中),我总是会收到重复的 Key 错误。我究竟做错了什么?

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

标签: flutterkeyflutter-animatedlist

解决方案


我解决了我的问题。

您不能将自定义键命名为“键”。这将导致问题。

如果您将其重命名为“customKey”之类的名称,它将起作用。

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

推荐阅读