【问题标题】:Animated List Multiple widgets used the same GlobalKey动画列表多个小部件使用相同的 GlobalKey
【发布时间】:2021-07-01 07:21:15
【问题描述】:

我正在尝试将 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,
    );
  }
}

【问题讨论】:

    标签: flutter key flutter-animatedlist


    【解决方案1】:

    我解决了我的问题。

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

    如果您将其重命名为“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,
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-26
      • 2019-06-07
      • 2020-10-01
      • 1970-01-01
      • 2021-08-26
      • 2023-03-04
      • 2019-06-01
      • 1970-01-01
      • 2020-10-21
      相关资源
      最近更新 更多