Flutter syncfusion DataGridview Force Cell on canSubmitCell · Issue #1144 · syncfusion/flutter

您所在的位置:网站首页 columnname Flutter syncfusion DataGridview Force Cell on canSubmitCell · Issue #1144 · syncfusion/flutter

Flutter syncfusion DataGridview Force Cell on canSubmitCell · Issue #1144 · syncfusion/flutter

2023-03-26 03:22| 来源: 网络整理| 查看: 265

if user input value force to select valid value untill dont go to other cell. if he clear cell then he can go to next cell. please help how to achive this. image import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:syncfusion_flutter_datagrid/datagrid.dart'; import 'package:collection/collection.dart'; import 'package:tag/widgets/search_grid.dart';

class MainGridPage extends StatefulWidget { const MainGridPage({Key? key}) : super(key: key); @OverRide State createState() => _MainPageState(); }

class _MainPageState extends State { List firstgridflieds = []; List datalist1 = []; List datalist2 = []; @OverRide void initState() { firstgridflieds = [ GridFields(FieldName: 'Name', InputType: 'search', ReadOnly: false), GridFields(FieldName: 'Quantity', InputType: 'number', ReadOnly: false), GridFields(FieldName: 'Price', InputType: 'decimal', ReadOnly: false), GridFields(FieldName: 'Amount', InputType: 'number', ReadOnly: true), ];

datalist1.add({"Name":'Name 1',"Quantity":10,"Price":5,"Amount":50}); // TODO: implement initState super.initState();

}

@OverRide Widget build(BuildContext context) { return Scaffold(body: SingleChildScrollView(child: DataGridView(gridfields:firstgridflieds,datalist: datalist1,),)

); } }

class DataGridView extends StatefulWidget { final List gridfields; final List datalist; const DataGridView({Key? key,required this.gridfields,required this.datalist}) : super(key: key);

@OverRide State createState() => _DataGridViewState(); }

class _DataGridViewState extends State {

@OverRide void dispose() { dataGridController.dispose(); // TODO: implement dispose super.dispose(); }

DataGridController dataGridController = new DataGridController(); late EmployeeDataSource _employeeDataSource; late CustomSelectionManager _customSelectionManager;

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

_customSelectionManager = CustomSelectionManager(dataGridController); _employeeDataSource = EmployeeDataSource(widget.datalist, widget.gridfields,context); _employeeDataSource.addrow();

}

@OverRide Widget build(BuildContext context) { return SfDataGrid( selectionMode: SelectionMode.single, navigationMode: GridNavigationMode.cell, editingGestureType: EditingGestureType.tap, selectionManager: _customSelectionManager, allowEditing: true, source: _employeeDataSource, controller: dataGridController, headerGridLinesVisibility: GridLinesVisibility.both, gridLinesVisibility: GridLinesVisibility.both, columns: List.generate( widget.gridfields.length, (i) => GridColumn( columnName: widget.gridfields[i].FieldName, label: Container( alignment: Alignment.centerLeft, child: Text(widget.gridfields[i].FieldName)))), ); } }

class EmployeeDataSource extends DataGridSource { EmployeeDataSource(this.EmpList, this.GridColumnList,this._context) { updateDataGridRows(); }

updateDataGridRows() async { dataGridRows = EmpList.map((e) => DataGridRow( cells: List.generate( GridColumnList.length, (i) => DataGridCell( columnName: GridColumnList[i].FieldName, value: e[GridColumnList[i].FieldName])))).toList(); }

BuildContext _context; List EmpList = []; List GridColumnList = []; List dataGridRows = [];

/// Helps to hold the new value of all editable widget. /// Based on the new value we will commit the new value into the corresponding /// [DataGridCell] on [onSubmitCell] method. dynamic newCellValue = null;

/// Help to control the editable text in [TextField] widget. TextEditingController editingController = TextEditingController();

@OverRide List get rows => dataGridRows;

void addrow() { Map value = {}; EmpList.insert(EmpList.length, value);

updateDataGridRows(); notifyListeners();

}

@OverRide Future onCellSubmit(DataGridRow dataGridRow, RowColumnIndex rowColumnIndex, GridColumn column) async{ final dynamic oldValue = dataGridRow .getCells() .firstWhereOrNull((DataGridCell dataGridCell) => dataGridCell.columnName == column.columnName) ?.value ?? '';

final int dataRowIndex = dataGridRows.indexOf(dataGridRow); if (newCellValue == null || oldValue == newCellValue) { return; } else { // if new value found // set new value to Map List Row EmpList[dataRowIndex][column.columnName] = newCellValue; // get current row value Map currentrowvalues = EmpList[dataRowIndex]; // do calculation for other columns int quantity = 0; int price = 0; int amount = 0; quantity = int.tryParse(currentrowvalues.containsKey('Quantity') ? currentrowvalues['Quantity'].toString() : "0") ?? 0; price = int.tryParse(currentrowvalues.containsKey('Price') ? currentrowvalues['Price'].toString() : "0") ?? 0; amount = quantity * price; // set value to Amount Cell EmpList[dataRowIndex]["Amount"] = amount; // reset current row values after adding new cells currentrowvalues = EmpList[dataRowIndex]; // now assign new row values to GridRow through loop over each field GridColumnList.asMap().forEach((index, value) { // set new value to grid row dataGridRows[dataRowIndex].getCells()[index] = DataGridCell( columnName: value.FieldName, value: currentrowvalues.containsKey(value.FieldName) ? currentrowvalues[value.FieldName] : null); //notify listner to refresh cells notifyDataSourceListeners( rowColumnIndex: RowColumnIndex(rowColumnIndex.rowIndex, index)); }); // if current row is last row then add new row if (rowColumnIndex.rowIndex + 1 == rows.length) { addrow(); } }

}

@OverRide Future canSubmitCell(DataGridRow dataGridRow, RowColumnIndex rowColumnIndex, GridColumn column) async{ // TODO: implement canSubmitCell GridFields fieldmodel = GridColumnList.where( (element) => element.FieldName == column.columnName).single;

if(fieldmodel.InputType == "search" && newCellValue!=null) { // find value in base of input value from search dialog await dialogbox(rowColumnIndex); } return super.canSubmitCell(dataGridRow, rowColumnIndex, column);

}

Future dialogbox(RowColumnIndex rowColumnIndex) async{

List fruitlist = ["Apple","Orange","blueberry","banana"]; if(newCellValue.length>0) { fruitlist = fruitlist.where((food) => food.toLowerCase().contains(newCellValue)).toList(); if (fruitlist.length==1) { newCellValue = fruitlist[0]; return; } }

if (fruitlist.length>0) { showDialog( context: _context, builder: (context) { return AlertDialog( scrollable: true, shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.zero)), title: Container(width: 300, height: 300, child:

ListView.builder( itemCount: fruitlist.length, itemBuilder: (context, i) { return ListTile( title: Text(fruitlist[i].toString()), onTap: (){ String value = fruitlist[i]; newCellValue = value; Navigator.pop(context); }, ); }, ) )); });

}

}

@OverRide Widget? buildEditWidget(DataGridRow dataGridRow, RowColumnIndex rowColumnIndex, GridColumn column, CellSubmit submitCell) { // The new cell value must be reset. // To avoid committing the [DataGridCell] value that was previously edited // into the current non-modified [DataGridCell]. newCellValue = null;

// get current row values Map rowvalue = EmpList[rowColumnIndex.rowIndex]; // get current field model GridFields fieldmodel = GridColumnList.where( (element) => element.FieldName == column.columnName).single;

// extract cell value from current row and set to text field editingController.text = rowvalue.containsKey(column.columnName) ? rowvalue[column.columnName].toString() : ""; return TextField( autofocus: true, maxLines: 1, readOnly: fieldmodel.ReadOnly, controller: editingController, onChanged: (dynamic value) { if (value.isNotEmpty) { newCellValue = value; } }, decoration: InputDecoration( border: InputBorder.none, isDense: true, suffix: fieldmodel.InputType == "search"? ExcludeFocus( child:InkWell( child:Icon(Icons.search), onTap:()=>dialogbox(rowColumnIndex))):null)); }

@OverRide DataGridRowAdapter buildRow(DataGridRow row) { return DataGridRowAdapter( cells: row.getCells().map((e) { return Text( e.value != null ? e.value.toString() : "", // style:Theme.of(_context).textTheme.bodyText1, ); }).toList()); } }

// create grid fields dynamically class GridFields { final String FieldName; final String InputType; final bool ReadOnly; GridFields( {required this.FieldName, required this.InputType, required this.ReadOnly});

factory GridFields.fromJson(Map json) { return GridFields( FieldName: json['FieldName'], InputType: json['InputType'], ReadOnly: json['InputType']); } }

class CustomSelectionManager extends RowSelectionManager { CustomSelectionManager(this.dataGridController); DataGridController dataGridController; bool istabPressed = false; @OverRide Future handleKeyEvent(RawKeyEvent keyEvent) async{ istabPressed = true; if (keyEvent.logicalKey == LogicalKeyboardKey.tab) { super.handleKeyEvent(keyEvent); WidgetsBinding.instance.addPostFrameCallback((timeStamp) { dataGridController.beginEdit(dataGridController.currentCell); });

return; } super.handleKeyEvent(keyEvent);

} }



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3