How to Maintain the State of a DataGrid When Switching Between Tabs in a Flutter DataTable?
When switching between tabs, all the widgets undergo re-creation, causing the Flutter DataGrid to lose its previous state, including sorting, filtering, and scroll position settings.
STEP 1: Initialize the SfDataGrid widget with all the necessary properties. To maintain the state of the Flutter DataGrid, it is important to use the AutomaticKeepAliveClientMixin. By using this mixin, the Flutter DataGrid can be preserved in its current state. Override the method wantKeepAlive to return true, ensuring that the state is retained.
class DataGrid extends StatefulWidget {
const DataGrid({
super.key,
});
@override
State<DataGrid> createState() => DataGridState();
}
class _DataGridState extends State<DataGrid>
with AutomaticKeepAliveClientMixin<DataGrid>{
List<Employee> employees = <Employee>[];
late EmployeeDataSource employeeDataSource;
@override
void initState() {
super.initState();
employees = getEmployeeData();
employeeDataSource = EmployeeDataSource(employeeData: employees);
}
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
return SfDataGrid(
source: employeeDataSource,
columns: getColumns,
allowSorting: true,
allowFiltering: true,
columnWidthMode: ColumnWidthMode.fill)
)
)
}
}
STEP 2: Wrap your DataGrid widget in a TabBarView.
class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
late TabController _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(length: 2, vsync: this);
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Syncfusion Flutter DataGrid'),
bottom: TabBar(
controller: _tabController,
tabs: const [
Tab(text: 'Employees'),
Tab(text: 'Empty View'),
],
),
),
body: TabBarView(controller: _tabController, children: const [
DataGrid(),
Center(
child: Text('Empty View'),
),
]),
);
}
}
Download the example from GitHub.
Conclusion
I hope you enjoyed learning about how to maintain the State of a DataGrid When Switching Between Tabs in a Flutter DataTable (SfDataGrid).
You can refer to our Flutter DataGrid feature tour page to know about its other groundbreaking feature representations. You can also explore our Flutter DataGrid documentation to understand how to present and manipulate data.
For current customers, you can check out our Flutter Controls from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our Flutter DataGrid and other Flutter controls.
If you have any queries or require clarifications, please let us know in comments below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!