TabController 和 Riverpod?

问题描述 投票:0回答:2

我想在 TabControl 中显示来自 Riverpod StatenotifierProvider 的 AsyncValue 结果。在 StatefulWidget 中,我会像这样实现 TabController:

class Screen extends StatefulWidget {
  Screen({Key? key}) : super(key: key);

  @override
  State<Screen> createState() => _ScreenState();
}

class _ScreenState extends State<Screen> with TickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

如果我将此小部件转换为 ConsumerWidget,我将无法再混合在 TickerProvider 中,如果我坚持使用 StatefulWidget,我将无法访问 ref 以及提供商。

非常感谢您的帮助!

flutter flutter-animation riverpod flutter-riverpod
2个回答
0
投票

最后我决定使用 tab_provider 包而不是 TabController。外观相似,代码更清晰。


-1
投票

您可以使用

ConsumerStatefulWidget
来访问
ref
(并使用
TickerProviderStateMixin
mixin):

class Screen extends ConsumerStatefulWidget {
  const Screen({super.key});

  @override
  _ScreenState createState() => _ScreenState();
}

class _ScreenState extends ConsumerState<Screen> with TickerProviderStateMixin {

  late TabController _tabController;

  @override
  void initState() {
    super.initState();

    // "ref" can be used in all life-cycles of a StatefulWidget.
    ref.read(currentIndexProvider);

    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  void initState() {
    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    final index = ref.watch(currentIndexProvider);
    return Text('$index');
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }
}

更多信息ConsumerStatefulWidget

© www.soinside.com 2019 - 2024. All rights reserved.