要解决“AnimatedSwitcher与Riverpod不兼容”的问题,您可以尝试使用ProviderContainer
将AnimatedSwitcher
包装起来,以便在适当的时候重新创建AnimatedSwitcher
的子组件。
以下是一个示例代码:
import 'package:flutter/material.dart';
import 'package:riverpod/riverpod.dart';
class MyWidget extends ConsumerWidget {
@override
Widget build(BuildContext context, ScopedReader watch) {
final container = watch(myProvider);
final showAnimatedSwitcher = container.read(showAnimatedSwitcherProvider);
return ProviderListener(
provider: showAnimatedSwitcherProvider,
onChange: (context, bool newValue) {
if (!newValue) {
// 当 showAnimatedSwitcher 的值变为 false 时,重新创建 AnimatedSwitcher 的子组件
container.read(animatedSwitcherChildProvider).dispose();
container.read(animatedSwitcherChildProvider).state =
GlobalKey();
}
},
child: AnimatedSwitcher(
// 使用 ValueKey 来确保 AnimatedSwitcher 正确地切换子组件
key: ValueKey(showAnimatedSwitcher),
duration: Duration(milliseconds: 500),
child: showAnimatedSwitcher
? AnimatedSwitcherChild()
: container.read(animatedSwitcherChildProvider).state,
),
);
}
}
class AnimatedSwitcherChild extends StatefulWidget {
@override
AnimatedSwitcherChildState createState() => AnimatedSwitcherChildState();
}
class AnimatedSwitcherChildState extends State {
@override
void dispose() {
print('AnimatedSwitcherChild disposed');
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
width: 100,
height: 100,
color: Colors.blue,
);
}
}
final animatedSwitcherChildProvider = StateProvider>(
(ref) => GlobalKey(),
);
final showAnimatedSwitcherProvider = StateProvider((ref) => true);
final myProvider = ProviderContainer().addProviders([
Provider((ref) => GlobalKey()),
Provider((ref) => true),
]);
void main() {
runApp(
ProviderScope(
child: MaterialApp(
home: Scaffold(
body: MyWidget(),
floatingActionButton: FloatingActionButton(
onPressed: () {
// 切换 showAnimatedSwitcher 的值来触发 AnimatedSwitcher 的重新创建子组件
myProvider
.read(showAnimatedSwitcherProvider)
.state = !myProvider.read(showAnimatedSwitcherProvider).state;
},
child: Icon(Icons.add),
),
),
),
),
);
}
在上面的示例中,我们使用ProviderContainer
来存储和管理animatedSwitcherChildProvider
和showAnimatedSwitcherProvider
两个值。animatedSwitcherChildProvider
是StateProvider
,它持有GlobalKey
的实例。showAnimatedSwitcherProvider
是StateProvider
,它持有一个布尔值用于控制是否显示AnimatedSwitcher
。
在ProviderListener
中,我们监听showAnimatedSwitcherProvider
的变化。当showAnimatedSwitcher
的值变为false
时,我们通过dispose
方法销毁旧的AnimatedSwitcherChild
并重新创建一个新的GlobalKey
来替代。
在MyWidget
中,我们使用ProviderListener
和AnimatedSwitcher
来包裹子组件。当showAnimatedSwitcher
的值发生变化时,AnimatedSwitcher
会根据ValueKey
重新创建子组件。如果showAnimatedSwitcher
的值为true
,则显示AnimatedSwitcherChild
;否则,显示存储在animatedSwitcherChildProvider
中的子组件。
通过这种方式,我们可以在AnimatedSwitcher
和Riverpod
之间实现兼容性。
上一篇:AnimatedSwitcher无法如预期工作?小部件发生变化,但没有动画。
下一篇:AnimatedVectorDrawable:找不到要在VectorDrawable中进行动画的名称为空的目标。