Why everytime the widget rebuild, it will trigger the sfdatapager?

How to avoid the sfdatapager being trigger, bcs i have a features to add and delete item, so example currently i am in page 3 and I add an item, so i have the loadSamePage features, where I will stay on the same page but dunt know where it will trigger the sfdatapager, so causing the handlePageChange load.... Image_4203_1702015567948


3 Replies

WP WONG PEI SAN A20EC0170 December 8, 2023 06:10 AM UTC

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:musix_v2/function/stores/stores_page_controller.dart';
import 'package:syncfusion_flutter_core/theme.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:pager/pager.dart';

class ViewStore extends StatefulWidget {
const ViewStore({super.key});

@override
State<ViewStore> createState() => _ViewStoreState();
}

class _ViewStoreState extends State<ViewStore> {
StoresPageController controller = Get.find<StoresPageController>();

@override
Widget build(BuildContext context) {
print('ViewStore:build');
// // if (filteredStoreList.isNotEmpty ||
// // (filteredStoreList.isEmpty && searchNotFound == true)) {
// // _stores.pagedList = _stores.storesList;
// // } else if (filteredStoreList.isEmpty &&
// // searchNotFound == false) {
// // Text('Store Not Found');
// // _stores.pagedList = [];
// // }
return Container(
margin: const EdgeInsets.only(
left: 24,
right: 24,
),
child: Column(
children: [
const SizedBox(height: 40),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Flexible(
flex: 3,
child: TextButton(
onPressed: () {
controller.page.value = 'addStore';
},
style: TextButton.styleFrom(
backgroundColor: const Color(0xFFF35539),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
),
child: Obx(
() => Text(
controller.buttonText.value,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
),
),
Flexible(
flex: 3,
child: Container(
margin: const EdgeInsets.only(left: 15, right: 15),
child: TextButton(
onPressed: () {},
style: TextButton.styleFrom(
backgroundColor: const Color(0xFFF9E5E2),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
),
child: const Text(
'Reset Play Q',
style: TextStyle(
fontFamily: 'Nunito',
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
),
),
),
Flexible(
flex: 2,
child: Container(
margin: const EdgeInsets.only(right: 15),
child: SizedBox(
width: 178,
height: 28,
child: TextField(
// controller: controller,
decoration: const InputDecoration(
contentPadding: EdgeInsets.only(bottom: 15.0),
filled: true,
fillColor: Colors.white,
prefixIcon: Icon(Icons.search),
hintText: "Search",
),
onSubmitted: (value) {
// setState(() {
// filteredStoreList =
// originalStoreList.where((element) {
// return element.name?.contains(value) ==
// true;
// }).toList();
//
// if (filteredStoreList.isEmpty) {
// searchNotFound = true;
// } else if (filteredStoreList.isNotEmpty) {
// searchNotFound = false;
// }
// });
},
),
),
),
),
],
),
const Divider(
height: 10,
color: Color(0xFF9DA19D),
thickness: 1,
),
SizedBox(
// width: constraints.maxWidth,
height: 425,
child: SfDataGridTheme(
data: SfDataGridThemeData(headerColor: const Color(0xffD4CDC8)),
child: SfDataGrid(
source: controller.storeDataSource,
columnWidthMode: ColumnWidthMode.fitByColumnName,
showCheckboxColumn: true,
selectionMode: SelectionMode.multiple,
controller: controller.dataGridController,
showVerticalScrollbar: false,
onSelectionChanged: (a, b) {
if (controller.dataGridController.selectedRows.isEmpty) {
controller.buttonText('Add Store');
} else {
controller.buttonText('Subscribe');
}
},
columns: [
GridColumn(
columnName: 'storesName',
columnWidthMode: ColumnWidthMode.lastColumnFill,
label: Row(
children: [
const Text(
'Store Name',
style: TextStyle(
fontWeight: FontWeight.bold,
decoration:
TextDecoration.underline, // Add underline
color: Color(0xFF0F62FE),
),
softWrap: false,
),
IconButton(
splashRadius: 0.0005,
padding: EdgeInsets.zero,
constraints:
const BoxConstraints(minWidth: 22, minHeight: 22),
icon: const Image(
image: AssetImage('assets/sort.png'),
),
onPressed: () {
// setState(() {
// // DBService.sortColumn = 'name';
// // DBService.sortPattern =
// // !DBService.sortPattern;
// // DBService.lastStoreDoc = null;
// });
},
),
],
),
),
GridColumn(
columnName: 'storesPlayQ',
label: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Has Play Q?',
style: TextStyle(
fontWeight: FontWeight.bold,
decoration:
TextDecoration.underline, // Add underline
color: Color(0xFF0F62FE),
),
softWrap: false,
),
IconButton(
splashRadius: 0.0005,
padding: EdgeInsets.zero,
constraints:
const BoxConstraints(minWidth: 22, minHeight: 22),
icon: const Image(
image: AssetImage('assets/sort.png'),
),
onPressed: () {
// setState(() {
// DBService.sortColumn = 'hasPlayedQ';
// DBService.sortPattern =
// !DBService.sortPattern;
// DBService.lastStoreDoc = null;
// });
},
),
],
),
),
GridColumn(
columnName: 'plan',
width: 90,
label: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Plan',
style: TextStyle(
fontWeight: FontWeight.bold,

decoration:
TextDecoration.underline, // Add underline
color: Color(0xFF0F62FE),
),
softWrap: false,
),
IconButton(
splashRadius: 0.0005,
padding: EdgeInsets.zero,
constraints:
const BoxConstraints(minWidth: 22, minHeight: 22),
icon:
const Image(image: AssetImage('assets/sort.png')),
onPressed: () {
// setState(() {
// DBService.sortColumn = 'plan';
// DBService.sortPattern =
// !DBService.sortPattern;
// DBService.lastStoreDoc = null;
// });
},
),
],
),
),
GridColumn(
columnName: 'currency',
label: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Curr',
style: TextStyle(
fontWeight: FontWeight.bold,
decoration:
TextDecoration.underline, // Add underline
color: Color(0xFF0F62FE),
),
softWrap: false,
),
IconButton(
splashRadius: 0.0005,
padding: EdgeInsets.zero,
constraints:
const BoxConstraints(minWidth: 22, minHeight: 22),
icon: const Image(
image: AssetImage('assets/sort.png'),
),
onPressed: () {
// setState(() {
// DBService.sortColumn = 'currency';
// DBService.sortPattern =
// !DBService.sortPattern;
// DBService.lastStoreDoc = null;
// });
},
),
],
),
),
GridColumn(
columnName: 'storesSubsStartEnd',
minimumWidth: 190,
label: Container(
alignment: Alignment.center,
child: const Text(
'Billing Period',
style: TextStyle(
fontWeight: FontWeight.bold,
),
softWrap: false,
),
),
),
GridColumn(
columnName: 'storesSubsEnd',
label: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Subs Ends',
style: TextStyle(
fontWeight: FontWeight.bold,
decoration:
TextDecoration.underline, // Add underline
color: Color(0xFF0F62FE),
),
softWrap: false,
),
IconButton(
splashRadius: 0.0005,
padding: EdgeInsets.zero,
constraints:
const BoxConstraints(minWidth: 22, minHeight: 22),
icon: const Image(
image: AssetImage('assets/sort.png'),
),
onPressed: () {
// setState(() {
// DBService.sortColumn = 'subsEndDt';
// DBService.sortPattern =
// !DBService.sortPattern;
// DBService.lastStoreDoc = null;
// });
},
),
],
),
),
GridColumn(
columnName: 'storesStatus',
label: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Status',
style: TextStyle(
fontWeight: FontWeight.bold,
decoration:
TextDecoration.underline, // Add underline
color: Color(0xFF0F62FE),
),
softWrap: false,
),
IconButton(
splashRadius: 0.0005,
padding: EdgeInsets.zero,
constraints:
const BoxConstraints(minWidth: 22, minHeight: 22),
icon: const Image(
image: AssetImage('assets/sort.png'),
),
onPressed: () {
// setState(() {
// DBService.sortColumn = 'subsEndDt';
// DBService.sortPattern =
// !DBService.sortPattern;
// DBService.lastStoreDoc = null;
// });
},
),
],
),
),
GridColumn(
columnName: 'deleteStores',
label: Container(),
),
],
),
),
),
SfDataPagerTheme(
data: SfDataPagerThemeData(
backgroundColor: Colors.transparent,
selectedItemColor: Colors.indigo.shade500),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
// Obx(() => Text(
// '${_stores.startIndex} - ${_stores.endIndex} of $storesLength',
// style: TextStyle(
// fontSize: 15,
// color: Color(0xFFA6A3A3),
// ),
// )),
SizedBox(
child: Obx(
() => SfDataPager(
// initialPageIndex:
// controller.newPageIndex, //deleteStore no need this
pageCount: controller.latestPageCount.value as double,
visibleItemsCount: 1,
direction: Axis.horizontal,
delegate: controller.storeDataSource,
onPageNavigationStart: (x) {
print('onPageNavigationStart');
// return true;
},
onPageNavigationEnd: (y) {
print('onPageNavigationEnd');
},
),
),
),
// ),
// Pager(
// currentPage: controller.newPageIndex ?? 1,
// totalPages: controller.latestPageCount.value,
// onPageChanged: (page) {
// setState(() {
// controller.newPageIndex = page;
// });
// },
// ),
],
),
),
],
),
);
}
}

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:get/get.dart';
import 'package:musix_v2/function/stores/storeDataSource.dart';
import 'package:musix_v2/function/stores/stores_page_controller.dart';
import '../../firestore/db_service.dart';
import '../../firestore/models/stores_model.dart';

class AddStore extends StatelessWidget {
AddStore({super.key});

final StoresPageController controller = Get.find<StoresPageController>();

@override
Widget build(BuildContext context) {
return Container(
color: const Color(0xFFEAE6E5),
padding:
const EdgeInsets.only(left: 25.0, right: 25, top: 20, bottom: 20),
child: Column(
children: [
Container(
padding: const EdgeInsets.all(10.0),
color: const Color(0xFFDCD6D3),
child: const Row(
children: [
Icon(Icons.info_outline),
SizedBox(width: 5),
Text(
'Info',
style: TextStyle(fontFamily: 'Roboto', fontSize: 18),
),
SizedBox(width: 20),
Image(
image: AssetImage('assets/Stack.png'),
),
SizedBox(width: 5),
Text(
'Play Queue',
style: TextStyle(fontFamily: 'Roboto', fontSize: 18),
),
],
),
),
const SizedBox(height: 10),
Container(
color: Colors.white,
padding: const EdgeInsets.all(10.0),
child: FormBuilder(
key: controller.formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Store Name',
style: TextStyle(fontFamily: 'Nunito', fontSize: 18),
),
const SizedBox(height: 10),
Row(
children: [
Flexible(
flex: 3,
child: FormBuilderTextField(
name: 'storeName',
controller: controller.sName,
decoration: const InputDecoration(
border: OutlineInputBorder(),
),
validator: FormBuilderValidators.compose([
FormBuilderValidators.required(),
]),
),
),
Flexible(
flex: 1,
child: Container(),
),
],
),
const SizedBox(height: 15),
const Text(
'Address',
style: TextStyle(fontFamily: 'Nunito', fontSize: 18),
),
const SizedBox(height: 10),
Row(
children: [
Flexible(
flex: 2,
child: FormBuilderTextField(
name: 'sAddress',
controller: controller.sAddress,
maxLines: 8,
decoration: const InputDecoration(
border: OutlineInputBorder(),
),
validator: FormBuilderValidators.compose([
FormBuilderValidators.required(),
]),
),
),
const SizedBox(width: 20),
const Flexible(
flex: 1,
child: Text(
'Main Store',
style: TextStyle(fontFamily: 'Nunito', fontSize: 18),
),
),
const SizedBox(width: 10),
SizedBox(
width: 50.0,
height: 25.0,
child: Obx(
() => CupertinoSwitch(
value: controller.isMainStore.value,
activeColor: const Color(0xFF1847ED),
onChanged: (value) {
controller.isMainStore.value = value;
},
),
),
),
],
),
const SizedBox(height: 20),
Row(
children: [
SizedBox(
width: 100,
height: 40,
child: TextButton(
onPressed: () {
controller.sName.clear();
controller.sAddress.clear();
controller.isMainStore.value = false;
controller.page.value = 'viewStore';
},
style: TextButton.styleFrom(
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(
side: const BorderSide(
color: Color(0xFFF35539),
),
borderRadius: BorderRadius.circular(6),
),
),
child: const Text(
'Cancel',
style: TextStyle(
fontFamily: 'Nunito',
fontSize: 16,
color: Color(0xFFF35539),
),
),
),
),
const SizedBox(width: 20),
SizedBox(
width: 100,
height: 40,
child: TextButton(
onPressed: () async {
saveNewStores();
},
style: TextButton.styleFrom(
backgroundColor: const Color(0xFFF9E5E2),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
),
child: const Text(
'Save',
style: TextStyle(
fontFamily: 'Nunito',
fontSize: 16,
color: Color(0xFFF35539),
),
),
),
),
],
),
],
),
),
),
],
),
);
}

void saveNewStores() {
if (controller.formKey.currentState!.validate()) {
Get.defaultDialog(
title: controller.sName.text,
middleText: 'Do you want to save this new store?',
actions: [
ElevatedButton(
onPressed: () async {
Map<String, dynamic> newStore = StoresModel().setData(
newStoresName: controller.sName.text,
newStoresAddress: controller.sAddress.text,
newStoresIsMain: controller.isMainStore.value,
newStoresCreatedAt: Timestamp.now(),
newStoresCreatedBy: DBService.getUserFullName(),
);
if (controller.isMainStore.value == true) {
await DBService.setNotMainStores();
}

controller.storeID = await DBService.addStores(newStore);
controller.sName.clear();
controller.sAddress.clear();
controller.isMainStore.value = false;

await controller.getTotalStores();
if (controller.latestPageCount.value != controller.totalPages) {
controller.latestPageCount.value = controller.totalPages;
// controller.newPageIndex = controller.newPageIndex - 1;
}

if (controller.newPageIndex == 0) {
print('controller.newPageIndex == 0');
await controller.loadFirstPages();
} else if (controller.newPageIndex ==
(controller.totalPages - 1)) {
print('controller.newPageIndex == (controller.totalPages - 1)');
await controller.loadLastPages();
} else {
print('else');
await controller.loadSamePage();
}
controller.storeDataSource.populateRowsData(controller.pagedList);
controller.page('viewStore');
print('go to view page');
Get.back();
},
child: const Text('Yes'),
),
ElevatedButton(
onPressed: () {
Get.back();
},
child: const Text('No'),
),
],
);
}
}
}



WP WONG PEI SAN A20EC0170 December 8, 2023 06:19 AM UTC

This is the video to help u get a better understanding of my current problem


Attachment: sfdatapager_a06c1383.rar


TP Tamilarasan Paranthaman Syncfusion Team December 11, 2023 03:01 PM UTC

Hi Wong Pei San,


Based on the provided code snippet and video reference, it appears that you are deleting the row and subsequently invoking `notifyListeners` from the DataGridSource class.


In the DataGrid implementation, triggering `notifyListeners` from the DataGridSource would consequently trigger the SfDataPager due to the inherent behavior of the DataGrid. To address this issue, consider using `setState` to refresh the view instead of calling `notifyListeners`. This approach might offer a resolution to the issue you are experiencing. Please check the following sample code snippet.


class MyHomePageState extends State<MyHomePage> {

 

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(title: const Text('Syncfusion Flutter DataGrid')),

      body: LayoutBuilder(

        builder: (BuildContext context, BoxConstraints constraints) {

          return Column(

            children: [

              SizedBox(

                height: constraints.maxHeight - 60,

                child: SfDataGrid(

                  source: _employeeDataSource,

                  rowsPerPage: rowsPerPage,

                  columns: getColumns,

                  columnWidthMode: ColumnWidthMode.fill,

                ),

              ),

              SizedBox(

                height: 60,

                width: constraints.maxWidth,

                child: SfDataPager(

                  pageCount: pageCount,

                  delegate: _employeeDataSource,

                  onPageNavigationStart: (int index) {

                    print('onPageNavigationStart');

                  },

                  onPageNavigationEnd: (int pageIndex) {

                    print('onPageNavigationEnd');

                  },

                ),

              ),

            ],

          );

        },

      ),

      floatingActionButton: FloatingActionButton(

        onPressed: () {

          setState(() {

            _employees.removeAt(_employees.length - 1);

            pageCount = (_employees.length / rowsPerPage).ceilToDouble();

            _employeeDataSource.dataGridRows

                .removeAt(_employeeDataSource.dataGridRows.length - 1);

            // don't call notifyListeners() method from the _employeeDataSource class,

            // because it will rebuild the datapager widget.

            // example: _employeeDataSource.updateDataGridSource();

          });

        },

        child: const Tooltip(

            message: 'Delete Last Row', child: Icon(Icons.delete)),

      ),

    );

  }


Regards,

Tamilarasan


Attachment: Recording_20231211_163355_25937149.zip

Loader.
Up arrow icon