首页 > 解决方案 > AnimatedSwitcher 在 ReorderableListView 中不起作用

问题描述

我试图让 AnimatedSwitcher 在 ReorderableListView 中工作,它在普通 ListView 中工作。我认为它与钥匙有关,但我现在确定。

Flutter 1.17.0 • 频道测试版 • https://github.com/flutter/flutter.git 框架 • 修订版 e6b34c2b5c(7 天前) • 2020-05-02 11:39:18 -0700 引擎 • 修订版 540786dd51 工具 • Dart 2.8.1

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => ChangeNumber(),
      child: MaterialApp(
        title: 'Flutter Demo',
        home: Scaffold(
          body: SafeArea(
            child: Consumer<ChangeNumber>(
              builder: (context, value, child) {
                return Column(
                  children: <Widget>[
                    Container(
                      height: 100,
                      child: ReorderableListView(
                        onReorder: (oldIndex, newIndex) {},
                        children: <Widget>[
                          AnimatedSwitcher(
                            key: ValueKey(value.i),
                            duration: Duration(seconds: 1),
                            child: NumberTile(
                              number: value.i,
                              key: ValueKey(value.i),
                            ),
                          ),
                        ],
                      ),
                    ),
                    RaisedButton(
                      child: Text('Increase'),
                      onPressed: () => value.i = value.i + 1,
                    )
                  ],
                );
              },
            ),
          ),
        ),
      ),
    );
  }
}

class NumberTile extends StatelessWidget {
  final int number;

  NumberTile({this.number, key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text('$number'),
    );
  }
}

class ChangeNumber extends ChangeNotifier {
  int _i = 0;

  get i => _i;

  set i(int value) {
    _i = value;
    notifyListeners();
  }
}

标签: flutterdartflutter-animation

解决方案


AnimatedSwitcher不会在Text小部件上显示效果,因为您TextListTile里面NumberTile。您必须将要为开关设置动画的直接小部件放置在AnimatedSwitcher. 检查这个例子


推荐阅读