Como construir um TabView usando Flutter GetX
Estou tentando construir um aplicativo usando Flutter com GetX para gerenciamento de estado, e em uma das minhas páginas eu preciso construir um widget TabView no meio da página, já encontrei um monte de coisas explicando como construir um TabView como widget, como este post e este artigo , mas todos eles estendem um controlador de estado com um SingleTickerProviderStateMixin .
Pelo que entendi lendo a documentação, não devo usar StatefulWidgets e States assim, mas não consigo descobrir como elaborar uma solução usando a arquitetura GetX.
Já experimentei na minha página coisas como:
class CourseDetailPage extends StatelessWidget {
final TabController _tabController = Get.put(TabController(vsync: null, length: 2));
}
e
class CourseDetailPage extends StatelessWidget {
final TabController _tabController = TabController(vsync: null, length: 2);
}
Mas o argumento VSYNC para o TabController não pode ser nulo, e não descobri como não consigo obter um TickerProvider para preenchê-lo.
Respostas
O seguinte seria uma solução para usar um controlador GetX para controlar um TabView?
GetTicker
Há uma versão Get de SingleTickerProviderMixin que implementa a interface TickerProvider (usando a mesma classe Ticker do Flutter SDK).
Tem um nome cativante: SingleGetTickerProviderMixin
The below example is basically from the Flutter docs for TabController.
From the linked example's StatefulWidget I transplated its contents into a GetxController (MyTabController) and added mixin of SingleGetTickerProviderMixin:
class MyTabController extends GetxController with SingleGetTickerProviderMixin {
final List<Tab> myTabs = <Tab>[
Tab(text: 'LEFT'),
Tab(text: 'RIGHT'),
];
TabController controller;
@override
void onInit() {
super.onInit();
controller = TabController(vsync: this, length: myTabs.length);
}
@override
void onClose() {
controller.dispose();
super.onClose();
}
}
To use MyTabController inside a Stateless widget:
class MyTabbedWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final MyTabController _tabx = Get.put(MyTabController());
// ↑ init tab controller
return Scaffold(
appBar: AppBar(
bottom: TabBar(
controller: _tabx.controller,
tabs: _tabx.myTabs,
),
),
body: TabBarView(
controller: _tabx.controller,
children: _tabx.myTabs.map((Tab tab) {
final String label = tab.text.toLowerCase();
return Center(
child: Text(
'This is the $label tab',
style: const TextStyle(fontSize: 36),
),
);
}).toList(),
),
);
}
}
Here's the rest of the app example to just copy & paste into Android Studio / VisualStudio Code to run:
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('GetX Tab Example'),
),
body: Column(
children: [
Expanded(
flex: 1,
child: Container(
alignment: Alignment.center,
child: Text('Some random stuff'),
),
),
Expanded(
flex: 4,
child: MyTabbedWidget(),
)
],
),
);
}
}
class MyTabController extends GetxController with SingleGetTickerProviderMixin {
final List<Tab> myTabs = <Tab>[
Tab(text: 'LEFT'),
Tab(text: 'RIGHT'),
];
TabController controller;
@override
void onInit() {
super.onInit();
controller = TabController(vsync: this, length: myTabs.length);
}
@override
void onClose() {
controller.dispose();
super.onClose();
}
}
class MyTabbedWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final MyTabController _tabx = Get.put(MyTabController());
// ↑ init tab controller
return Scaffold(
appBar: AppBar(
bottom: TabBar(
controller: _tabx.controller,
tabs: _tabx.myTabs,
),
),
body: TabBarView(
controller: _tabx.controller,
children: _tabx.myTabs.map((Tab tab) {
final String label = tab.text.toLowerCase();
return Center(
child: Text(
'This is the $label tab',
style: const TextStyle(fontSize: 36),
),
);
}).toList(),
),
);
}
}
As you said in all articles they extend State with SingleTickerProviderStateMixin because you won't be able to initialize your TabController outside of a State as TabController manage a state (doc).
A workaround would be to not use a variable for your controller and wrap your TabBar and TabView widget tree inside a DefaultTabController.
Here is an example from the official doc:
class MyDemo extends StatelessWidget {
final List<Tab> myTabs = <Tab>[
Tab(text: 'LEFT'),
Tab(text: 'RIGHT'),
];
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: myTabs.length,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: myTabs,
),
),
body: TabBarView(
children: myTabs.map((Tab tab) {
final String label = tab.text.toLowerCase();
return Center(
child: Text(
'This is the $label tab',
style: const TextStyle(fontSize: 36),
),
);
}).toList(),
),
),
);
}
}
By doing so you won't need to have your TabView inside a State but you won't be using GetX either.
I came across the exact issue and it shows that the GetX framework is not ready for many possible scenarios and you should use it cautiously.
The solution I came up with is a wrapper widget. In the proposed example I used HookWidget but you are free to use Stateful widget as well.
class TabWidget extends HookWidget {
final List<Widget> children;
final RxInt currentTab;
final int initialIndex;
TabWidget({
@required this.children,
@required this.currentTab,
@required this.initialIndex,
});
@override
Widget build(BuildContext context) {
final controller = useTabController(
initialLength: children.length,
initialIndex: initialIndex,
);
currentTab.listen((page) {
controller.animateTo(page);
});
return TabBarView(controller: controller, children: children);
}
}
As you can see there is a Rx variable which controls the state of the tabView. So you have to pass a RxInt from the outside and whenever the value of it changes, the tabView updates respectively.
class TestView extends GetView<TestController> {
@override
Widget build(BuildContext context) {
final screen = 0.obs;
return SafeArea(
child: Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: Icon(Icons.forward),
onPressed: () => screen.value = screen.value + 1,
)
],
),
body: TabWidget(
initialIndex: 1,
currentTab: screen,
children: [
child1,
child2,
child3,
...,
],
),
),
);
}
Right now we take care of the controller by the help of HookWidget. If you are using Stateful widget you have to dispose it correctly.