flutter - 动画列表多个小部件使用相同的 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,
);
}
}
解决方案
我解决了我的问题。
您不能将自定义键命名为“键”。这将导致问题。
如果您将其重命名为“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,
);
}
}
推荐阅读
- .net-core - 多平台编译:System.Configuration.ConfigurationManager.GetSection 在 .NetCore 上抛出错误
- r - 将 DF 列值转换为 R 中的矩阵
- mysql - 错误:安装 mysqlclient 时命令“gcc”失败,退出状态为 1
- python - 为什么在 Pool 中使用超过 2 个进程后没有影响?
- awk - 如何用 awk 对重复行的值求和?
- angular - Angular 6 - 带有子类型的 catchError
- spring - 为什么我得到 org.springframework.beans.NotReadablePropertyException?
- c# - 使用正则表达式在字符串中查找特定模式的所有匹配项
- java - PCF App to App Oauth 2 grant_type = 'client_credentials' 和范围 uaa.resources。本地测试
- tableau-api - 混合 lod 和 non-lod 计算