How to dynamically add dynamic List value into Flutter DataTable? - flutter

I have dynamic List as shown below:
List<List<dynamic>> _userTransactionList;
The List contains these values:
[
[12.9, test, 80, 357.24, James],
[88.0, test, 19, 357.24, Carol],
[196.55, test, 34, 357.24, Matthew],
[48.0, test, 59, 357.24, Brown]
]
As shown above, my _userTransactionList length is 4. I need 3 column as:
Name Age Amount
And row cell will be:
Name Age Amount
James 80 12.9
Carol 19 88.0
Matthew 34 199.55
Brown 59 48.0
I can place the cell value manually as shown below, but I don't know how to get those value from list and add to row cells dynamically. Because of my List<List> _userTransactionList values comes from remote server I need to fill DataTable dynamically. Any idea?
Manual Code:
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable(
columnSpacing: 30.0,
columns: <DataColumn>[
DataColumn(
label: Text(
'Name',
style: TextStyle(color: Colors.deepOrange, fontWeight: FontWeight.bold),
),
),
DataColumn(
label: Text(
'Age',
style: TextStyle(color: Colors.deepOrange, fontWeight: FontWeight.bold),
),
),
DataColumn(
label: Text(
'Amount',
style: TextStyle(color: Colors.deepOrange, fontWeight: FontWeight.bold),
),
),
DataColumn(
label: Text(
'Mail',
style: TextStyle(color: Colors.deepOrange, fontWeight: FontWeight.bold),
),
),
],
rows: <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(Text('James')),
DataCell(Text('80')),
DataCell(Text('12.9')),
DataCell(
IconButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('James 80 12.9'),
),
);
},
icon: Icon(
Icons.email_outlined,
color: Colors.red,
),
),
),
],
),
DataRow(
cells: <DataCell>[
DataCell(Text('Carol')),
DataCell(Text('19')),
DataCell(Text('88.0')),
DataCell(
IconButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Carol 19 88.0'),
),
);
},
icon: Icon(
Icons.email_outlined,
color: Colors.red,
),
),
),
],
),
DataRow(
cells: <DataCell>[
DataCell(Text('Matthew')),
DataCell(Text('34')),
DataCell(Text('199.55')),
DataCell(
IconButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Matthew 34 199.55'),
),
);
},
icon: Icon(
Icons.email_outlined,
color: Colors.red,
),
),
),
],
),
DataRow(
cells: <DataCell>[
DataCell(Text('Brown')),
DataCell(Text('59')),
DataCell(Text('48.0')),
DataCell(
IconButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Brown 59 48.0'),
),
);
},
icon: Icon(
Icons.email_outlined,
color: Colors.red,
),
),
),
],
),
],
),
);

Full Code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
static String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: Text(_title)),
body: MyStatelessWidget(),
),
);
}
}
class MyStatelessWidget extends StatelessWidget {
List<List<dynamic>> _userTransactionList = [
[12.9, "BxC", 80, 357.24, "James"],
[88.0, "ArD", 19, 145.00, "Carol"],
[196.55, "VsT", 34, 18.60, "Matthew"],
[48.0, "IhO", 59, 92.19, "Brown"]
];
#override
Widget build(BuildContext context) {
List<DataRow> rows = [];
for (var i = 0; i < _userTransactionList.length; i++) {
rows.add(DataRow(cells: [
DataCell(
Text(_userTransactionList[i][4].toString()),
),
DataCell(
Text(_userTransactionList[i][2].toString()),
),
DataCell(
Text(_userTransactionList[i][0].toString()),
),
DataCell(
IconButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Matthew 34 199.55'),
),
);
},
icon: Icon(
Icons.email_outlined,
color: Colors.red,
),
),
),
]));
}
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
//child: _getData01(_userTransactionList, context)
child: DataTable(
columnSpacing: 30.0,
columns: <DataColumn>[
DataColumn(
label: Text(
'Name',
style: TextStyle(color: Colors.deepOrange, fontWeight: FontWeight.bold),
),
),
DataColumn(
label: Text(
'Age',
style: TextStyle(color: Colors.deepOrange, fontWeight: FontWeight.bold),
),
),
DataColumn(
label: Text(
'Amount',
style: TextStyle(color: Colors.deepOrange, fontWeight: FontWeight.bold),
),
),
DataColumn(
label: Text(
'Mail',
style: TextStyle(color: Colors.deepOrange, fontWeight: FontWeight.bold),
),
),
],
rows: rows,
));
}
}

Related

How do I make this text field editable and not editable with a button. Dart/Flutter

how do I make the "title" text field editable when the edit button is pressed.
preferably the edit button should be at the right hand side of the app bar next to the done button.
Here is my code, ive removed most of the code for the other fields to save character limit for this post but kept the code for the "title" text field.
Thank You!
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class viewLossEvent extends StatefulWidget {
String code,
title,
orgUnit,
riskOfficer,
natureOfEvent,
islamicBusiness,
shariahRelated,
incidentType,
operationalRiskLossType,
countryOfEvent,
stateOfEvent,
districtOfEvent,
modusOperandi,
factOfIncident,
//Status Approval and Validation
status,
incidentOwner,
rejectionComment,
ormdRec,
reasonNotValid,
//Incident Categorization
busline1,
busline2,
busline3,
proServ,
delChannel,
causCat1,
causCat2,
causCat3,
causCatOth,
eventcat1,
eventcat2,
eventcat3,
boundOthRisk,
payInst,
cardBrand,
payChan,
cardType,
busAct,
accType,
depRisk,
riskAss,
riskRate,
//Fraud Related Information
possfraud,
iADRD,
iADF,
iADC,
//Incident Dates
discDate,
discTime,
occDate,
occTime,
resDate,
resTime,
subBNMDate,
dateIncRep,
recDate,
closeDate,
//Incident Loss Data
grossLoss,
recoveryAmmount,
netLoss,
recoveryEC,
contingentLia;
viewLossEvent(
{this.code,
this.title,
this.orgUnit,
this.riskOfficer,
this.natureOfEvent,
this.islamicBusiness,
this.shariahRelated,
this.incidentType,
this.operationalRiskLossType,
this.countryOfEvent,
this.stateOfEvent,
this.districtOfEvent,
this.modusOperandi,
this.factOfIncident,
this.status,
this.incidentOwner,
this.rejectionComment,
this.ormdRec,
this.reasonNotValid,
this.busline1,
this.busline2,
this.busline3,
this.proServ,
this.delChannel,
this.causCat1,
this.causCat2,
this.causCat3,
this.causCatOth,
this.eventcat1,
this.eventcat2,
this.eventcat3,
this.boundOthRisk,
this.payInst,
this.cardBrand,
this.payChan,
this.cardType,
this.busAct,
this.accType,
this.depRisk,
this.riskAss,
this.riskRate,
this.possfraud,
this.iADRD,
this.iADF,
this.iADC,
this.discDate,
this.discTime,
this.occDate,
this.occTime,
this.resDate,
this.resTime,
this.subBNMDate,
this.dateIncRep,
this.recDate,
this.closeDate,
this.grossLoss,
this.recoveryAmmount,
this.netLoss,
this.recoveryEC,
this.contingentLia});
#override
State<viewLossEvent> createState() => _viewLossEventState();
}
class _viewLossEventState extends State<viewLossEvent> {
int _selectedIndex = 0;
void _navigateBottomBar(int index){
setState(() {
_selectedIndex = index;
});
}
bool isReadOnly = true;
void _edit(){
setState(() {
isReadOnly = !isReadOnly;
});
}
List<Widget> _pages = [];
void initState() {
super.initState();
_pages = [
Container(
child: SingleChildScrollView(
child: Column(
children: [
//Main Info
ListTileTheme(
tileColor: Colors.grey,
child: ExpansionTile(
title: Text(
'Main Info',
style: GoogleFonts.poppins(textStyle: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 20,))
),
children: [
//Fields
ListTileTheme(
tileColor: Colors.white,
child: ListTile(
title: Text('Code : ${widget.code}',
style: GoogleFonts.poppins(textStyle: const TextStyle(
fontWeight: FontWeight.normal,
fontSize: 20,
),),),
),
),
ListTileTheme(
tileColor: Colors.white,
child: ListTile(
leading: Text(
'Title : ',
style: TextStyle(
fontSize: 20.0,
color: Colors.black,
fontWeight: FontWeight.bold
),
),
title: TextField(
readOnly: isReadOnly,
decoration: InputDecoration(
hintStyle: TextStyle(fontSize: 20.0, color: Colors.black),
hintText: '${widget.title}',
border: InputBorder.none,
),
),
),
),
],
),
),
),
Container(
child: SingleChildScrollView(
child: Column(
children: [
//Shariah Details
ListTileTheme(
tileColor: Colors.grey,
child: ExpansionTile(
title: Text(
'LE Shariah',
style: GoogleFonts.poppins(textStyle: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 20,))
),
children: [
//Fields
],),
),
],
),
),
),
Container(
child: SingleChildScrollView(
child: Column(
children: [
//Shariah Details
ListTileTheme(
tileColor: Colors.grey,
child: ExpansionTile(
title: Text(
'LE Attachment',
style: GoogleFonts.poppins(textStyle: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 20,))
),
children: [
//Fields
],),
),
],
),
),
),
Container(
child: SingleChildScrollView(
child: Column(
children: [
//Shariah Details
ListTileTheme(
tileColor: Colors.grey,
child: ExpansionTile(
title: Text(
'LE Action',
style: GoogleFonts.poppins(textStyle: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 20,))
),
children: [
//Fields
],),
),
],
),
),
),
Container(
child: SingleChildScrollView(
child: Column(
children: [
//Shariah Details
ListTileTheme(
tileColor: Colors.grey,
child: ExpansionTile(
title: Text(
'Compliance Incident',
style: GoogleFonts.poppins(textStyle: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 20,))
),
children: [
//Fields
],),
),
],
),
),
),
];
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: const Color(0xFF002d62),
title: Text('${widget.code}',
style: GoogleFonts.sora(
textStyle: const TextStyle(
fontSize: 25,
fontWeight: FontWeight.w500,
),
)),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.edit),
onPressed: _edit,
),
],
),
body: _pages[_selectedIndex],
bottomNavigationBar: BottomNavigationBar(
onTap: _navigateBottomBar,
currentIndex: _selectedIndex,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'General'),
BottomNavigationBarItem(icon: Icon(Icons.balance), label: 'LE Shariah'),
BottomNavigationBarItem(icon: Icon(Icons.attachment), label: 'LE Attachment'),
BottomNavigationBarItem(icon: Icon(Icons.call_to_action), label: 'LE Action'),
BottomNavigationBarItem(icon: Icon(Icons.person_pin_circle), label: 'Compliance Incident'),
]),
);
}
}
instaed of using enabled:
use readOnly: ,
bool isReadOnly = true;
this is how your textfield looks
TextField(
readOnly: isReadOnly,
decoration: InputDecoration(
hintStyle: TextStyle(fontSize: 20.0, color: Colors.black),
hintText: '${widget.title}',
border: InputBorder.none,
),
on your edit button
onTap:(){
setState(() {
isReadOnly = !isReadOnly;
});
}
You can set
enabled: isEditable in TextField
When You click on the Edit button set the value of isEditable
setState(() {
isEditable=!isEditable;
});

Flutter Search bar not displaying all the users

I have been implementing a search bar in Flutter, which works as expected when searching according to usernames, but does not display all the users when it is empty.
It only displays all the users when typing something in the search bar and completely backspacing it. The following code snippet shows its implementation:
class UsersTable extends StatefulWidget {
List<User> users;
List<Library> posts;
UsersTable(
this.users,
this.posts, {
Key? key,
}) : super(key: key);
#override
State<UsersTable> createState() => _UsersTableState();
}
class _UsersTableState extends State<UsersTable> {
List<User> _foundUsers = [];
#override
initState() {
// at the beginning, all users are shown
Future.delayed(Duration.zero, () async {
_foundUsers = widget.users;
print(_foundUsers.length);
if (mounted) setState(() {});
});
super.initState();
}
// This function is called whenever the text field changes
void _runFilter(String enteredKeyword) {
List<User> results = [];
if (enteredKeyword.trim().isEmpty) {
// if the search field is empty or only contains white-space, we'll display all users
results = widget.users;
print("if filter length");
print(results.length);
} else {
results = widget.users
.where((user) => user.username
.toLowerCase()
.contains(enteredKeyword.toLowerCase()))
.toList();
// we use the toLowerCase() method to make it case-insensitive
}
// Refresh the UI
setState(() {
_foundUsers = results;
});
}
Widget body(BuildContext context, List<User> users, List<Library> posts) {
return SafeArea(
child: Material(
child: Container(
padding: const EdgeInsets.all(defaultPadding),
decoration: const BoxDecoration(
color: boxColor,
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
const Align(
alignment: Alignment.center,
child: Text(
"Active Users",
//style: Theme.of(context).textTheme.subtitle1,
style: TextStyle(
color: Colors.white,
fontSize: 20,
decoration: TextDecoration.none),
)),
const SizedBox(
height: 30,
),
TextField(
style: const TextStyle(color: Colors.white),
onChanged: (value) => _runFilter(value),
decoration: const InputDecoration(
labelStyle: TextStyle(color: Colors.white38),
labelText: 'Search',
suffixIcon: Icon(Icons.search),
suffixIconColor: Colors.white),
),
const SizedBox(
height: 20,
),
// SizedBox(
//width: double.infinity,
// child: SingleChildScrollView(
Container(
child: DataTable(
columnSpacing: 7,
columns: const [
// DataColumn(
// label: Text(
// "First Name",
// style: TextStyle(color: Colors.white),
// ),
// ),
// DataColumn(
// label: Text(
// "Last Name",
// style: TextStyle(color: Colors.white),
// ),
// ),
DataColumn(
label: Text(
"Username",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
),
DataColumn(
label: Text(
"Email ID",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
),
// DataColumn(
// label: Text(
// "DOB",
// style: TextStyle(color: Colors.white),
// ),
// ),
DataColumn(
label: Text(
"Account\nType",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
),
DataColumn(
label: Text(
"Delete\nUser",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
),
DataColumn(
label: Text(
"View\nPosts",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
),
],
rows:
//_foundUsers.isNotEmpty?
_foundUsers
.map(
(user) => DataRow(
cells: <DataCell>[
// DataCell(Text(user.first_name,
// style: TextStyle(color: Colors.white))),
// DataCell(Text(user.last_name,
// style: TextStyle(color: Colors.white))),
DataCell(Text(user.username,
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white))),
DataCell(Text(user.email,
style: TextStyle(color: Colors.white))),
// DataCell(Text(user.date_of_birth,
// style: TextStyle(color: Colors.white))),
DataCell(Text(user.account_type,
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white))),
DataCell(
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.purple,
padding: const EdgeInsets.symmetric(
horizontal: 15, vertical: 15),
textStyle: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold),
shadowColor: Colors.grey,
),
onPressed: () {
// if (user.username
// .compareTo('hwumazijadmin48') !=
// 0) {
BlocProvider.of<AuthenticationBloc>(context)
.add(DeleteUser(
username: user.username));
// } else {
// const Text("Cannot Delete Admin");
// }
},
child: const Text('X'),
),
),
DataCell(
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.purple,
padding: const EdgeInsets.symmetric(
horizontal: 15, vertical: 15),
textStyle: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold),
shadowColor: Colors.grey,
),
onPressed: () {
List<Library> po = [];
int i = 0;
while (i < posts.length) {
if (posts[i]
.user
.compareTo(user.username) ==
0) {
po.add(posts[i]);
}
i++;
}
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PostsTable(po),
),
);
},
child: const Text('\u{1F441}'),
),
),
],
),
)
.toList()
//: []
),
),
// ),
],
),
)
//)
));
}
Am I missing something in the code?
move super.initState(); above and remove Future.delayed.
#override
initState() {
super.initState();
_foundUsers = widget.users;
}
no need to setState({}); because build method will trigger after initState. Also no need for mounted because we removed asyncoperation.

how to scroll by index in datatable flutter

I have 2000+ Rows in datatable and I want to scroll to DataRow.byIndex by search index
DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text(
'Number',
),
),
DataColumn(
label: Text(
'Amount',
),
),
DataColumn(
label: Text(
'Delete',
),
),
],
rows: [
for (int i = 0; i < _jodies.length; i++)
DataRow.byIndex(index: i, cells: <DataCell>[
DataCell(Text(_jodies[i]['number']
.toString()
.length ==
1
? '0${_jodies[i]['number'].toString()}'
: _jodies[i]['number'].toString())),
DataCell(Text(
_jodies[i]['amount'].toString(),
style: TextStyle(
color: selectedJodi == i
? Colors.red
: Colors.black))),
DataCell(
IconButton(
icon: new Icon(
Icons.delete_forever,
color: Colors.red,
size: 24.0,
),
highlightColor: Colors.red,
onPressed: () {
_showDeleteConfirmation(i, 'jodi');
},
),
),
]),
],
),
how can I scroll to particular row

flutter datatable how to add vertical border between columns

I have a data table like below with three columns and I want to add vertical border separator , divider or whatever it called between all columns-included header- is this available in flutter datatables and how to do this ?
thanks
as a side note : I tried multiple options but it is hard to minuplate like listview or json_table package
import 'package:flutter/material.dart';
import 'dart:math';
import 'package:talab/helpers/constant_helper.dart';
class TablesPage extends StatefulWidget {
#override
TablesPageState createState() => TablesPageState();
}
class TablesPageState extends State<TablesPage> {
// Generate a list of fiction prodcts
final List<Map> _products = List.generate(30, (i) {
return {"id": i, "name": "Product $i", "price": Random().nextInt(200) + 1};
});
int _currentSortColumn = 0;
bool _isAscending = true;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Kindacode.com'),
),
body: Container(
width: double.infinity,
child: SingleChildScrollView(
child: DataTable(
dividerThickness: 5,
decoration: BoxDecoration(
border:Border(
right: Divider.createBorderSide(context, width: 5.0),
left: Divider.createBorderSide(context, width: 5.0)
),
color: AppColors.secondaryColor,
),
showBottomBorder: true,
sortColumnIndex: _currentSortColumn,
sortAscending: _isAscending,
headingRowColor: MaterialStateProperty.all(Colors.amber[200]),
columns: [
DataColumn(label: Text('كود الطلب')
),
DataColumn(label: Text('الاشعار')),
DataColumn(
label: Text(
'التاريخ',
style: TextStyle(
color: Colors.blue, fontWeight: FontWeight.bold),
),),
],
rows: _products.map((item) {
return DataRow(cells: [
DataCell(Text(item['id'].toString())),
DataCell(Text(item['name'])),
DataCell(Text(item['price'].toString()))
]);
}).toList(),
),
),
));
}
}
As others have suggested, adding a vertical divider is one solution. Another is to use the DataTable's built-in border, which adds a border to every cell. It works like Border in the Decoration class. So, using your code example, the table can be defined:
DataTable(
border: TableBorder.all(
width: 5.0,
color:AppColors.secondaryColor,
dividerThickness: 5,
You can remove all of the other borders in your code. I believe this will give you the look you want.
As variant, you can use VerticalDivider widget. For example, define props of your vertical divider
Widget _verticalDivider = const VerticalDivider(
color: Colors.black,
thickness: 1,
);
and add it between header columns and cells
columns: [
DataColumn(label: Text('كود الطلب')),
DataColumn(label: _verticalDivider),
DataColumn(label: Text('الاشعار')),
DataColumn(label: _verticalDivider),
DataColumn(
label: Text(
'التاريخ',
style: TextStyle(
color: Colors.blue, fontWeight: FontWeight.bold),
),),
],
rows: _products.map((item) {
return DataRow(cells: [
DataCell(Text(item['id'].toString())),
DataCell(_verticalDivider),
DataCell(Text(item['name'])),
DataCell(_verticalDivider),
DataCell(Text(item['price'].toString()))
]);
}).toList(),
The following works for me:
DataTable(
showBottomBorder: true,
dividerThickness: 5.0,
columns: const <DataColumn>[
DataColumn(
label: Text(
'Name',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
DataColumn(
label: Text(''),
),
DataColumn(
label: Text(
'Age',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
DataColumn(
label: Text(''),
),
DataColumn(
label: Text(
'Role',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
],
rows: const <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(Text('Albert')),
DataCell(VerticalDivider()),
DataCell(Text('19')),
DataCell(VerticalDivider()),
DataCell(Text('Student')),
],
),
DataRow(
cells: <DataCell>[
DataCell(Text('Janine')),
DataCell(VerticalDivider()),
DataCell(Text('43')),
DataCell(VerticalDivider()),
DataCell(Text('Professor')),
],
),
DataRow(
cells: <DataCell>[
DataCell(Text('William')),
DataCell(VerticalDivider()),
DataCell(Text('27')),
DataCell(VerticalDivider()),
DataCell(Text('Associate Professor')),
],
),
],
)

Flutter DataTable select Row

I have a problem with DataTable in flutter. I want to change the state of the row, when the user click on one of them, but I found just how to do this "manually" with selected: true, inside DataRow.
How can I let the user select just a single row, and deselect the rest, by changing the state?
content: Column(
children: <Widget>[
DataTable(
columns: [
DataColumn(label: Text('Language')),
DataColumn(label: Text('Translation')),
],
rows: [
DataRow(selected: true, cells: [
DataCell(
Text(
"RO",
textAlign: TextAlign.left,
style: TextStyle(fontWeight: FontWeight.bold),
),
onTap: () {
setState(() {
color = Colors.lightBlueAccent;
});
},
),
DataCell(
TextField(
decoration: InputDecoration(
border: InputBorder.none, hintText: 'paine'),
),
),
]),
DataRow(cells: [
DataCell(
Text(
"EN",
textAlign: TextAlign.left,
style: TextStyle(fontWeight: FontWeight.bold),
), onTap: () {
print('EN is clicked');
}),
DataCell(
TextField(
decoration: InputDecoration(
border: InputBorder.none, hintText: 'bread'),
),
),
]),
DataRow(cells: [
DataCell(
Text(
"FR",
textAlign: TextAlign.left,
style: TextStyle(fontWeight: FontWeight.bold),
), onTap: () {
print('FR is clicked');
}),
DataCell(
TextField(
decoration: InputDecoration(
border: InputBorder.none, hintText: 'pain'),
),
),
]),
],
),
],
),
You can copy past run full code below
You can use condition in selected like this 0 == selectedIndex where 0 is DataRow index
and change selectedIndex in onSelectChanged
code snippet
int selectedIndex = -1;
...
rows: [
DataRow(
selected: 0 == selectedIndex,
onSelectChanged: (val) {
setState(() {
selectedIndex = 0;
});
},
...
DataRow(
selected: 1 == selectedIndex,
onSelectChanged: (val) {
setState(() {
selectedIndex = 1;
});
},
working demo
full code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Color color;
int selectedIndex = -1;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
children: <Widget>[
DataTable(
onSelectAll: (val) {
setState(() {
selectedIndex = -1;
});
},
columns: [
DataColumn(label: Text('Language')),
DataColumn(label: Text('Translation')),
],
rows: [
DataRow(
selected: 0 == selectedIndex,
onSelectChanged: (val) {
setState(() {
selectedIndex = 0;
});
},
cells: [
DataCell(
Text(
"RO",
textAlign: TextAlign.left,
style: TextStyle(fontWeight: FontWeight.bold),
),
onTap: () {
setState(() {
color = Colors.lightBlueAccent;
});
},
),
DataCell(
TextField(
decoration: InputDecoration(
border: InputBorder.none, hintText: 'paine'),
),
),
]),
DataRow(
selected: 1 == selectedIndex,
onSelectChanged: (val) {
setState(() {
selectedIndex = 1;
});
},
cells: [
DataCell(
Text(
"EN",
textAlign: TextAlign.left,
style: TextStyle(fontWeight: FontWeight.bold),
), onTap: () {
print('EN is clicked');
}),
DataCell(
TextField(
decoration: InputDecoration(
border: InputBorder.none, hintText: 'bread'),
),
),
]),
DataRow(
selected: 2 == selectedIndex,
onSelectChanged: (val) {
setState(() {
selectedIndex = 2;
});
},
cells: [
DataCell(
Text(
"FR",
textAlign: TextAlign.left,
style: TextStyle(fontWeight: FontWeight.bold),
), onTap: () {
print('FR is clicked');
}),
DataCell(
TextField(
decoration: InputDecoration(
border: InputBorder.none, hintText: 'pain'),
),
),
]),
],
),
],
),
),
);
}
}
When I needed to call something when I pressed on the DataRow I did the following:
DataRow(
onSelectChanged(_) {
// do something here
}
cells: [],
),
Maybe this will help?
EDIT: this is a simple example of how to select/deselect rows
import 'package:flutter/material.dart';
class Stack1 extends StatefulWidget {
#override
_Stack1State createState() => _Stack1State();
}
class _Stack1State extends State<Stack1> {
bool row1Selected = false;
bool row2Selected = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: DataTable(
columns: [
DataColumn(
label: Text('My Data'),
),
],
rows: [
DataRow(
selected: row1Selected,
onSelectChanged: (value) {
setState(() {
row1Selected = value;
});
},
cells: [
DataCell(
Text('Data 1'),
),
],
),
DataRow(
selected: row2Selected,
onSelectChanged: (value) {
setState(() {
row2Selected = value;
});
},
cells: [
DataCell(
Text('Data 2'),
),
],
),
],
),
);
}
}
DataTable(
dataTextStyle: TextStyle(
fontSize: 12,
),
headingTextStyle: TextStyle(fontSize: 12),
dataRowHeight: 100,
decoration: BoxDecoration(
color: Constants.backgroundColor,
borderRadius: BorderRadius.circular(20),
// border: Border.all(color: Colors.black),
boxShadow: [
BoxShadow(
color: Colors.grey,
spreadRadius: 2,
blurRadius: 2,
offset: Offset(1, 1),
),
],
),
dividerThickness: 2,
showCheckboxColumn: false,
onSelectAll: (value) {},
columns: [
DataColumn(
label: Text(
'Unit No.',
style: TextStyle(
fontWeight: FontWeight.bold, color: Constants.appColor2),
)),
DataColumn(
label: Text(
'Unit Type',
style: TextStyle(
fontWeight: FontWeight.bold, color: Constants.appColor2),
)),
DataColumn(
label: Text(
'Description',
style: TextStyle(
fontWeight: FontWeight.bold, color: Constants.appColor2),
)),
],
rows: List.generate(
data.length,
(index) => DataRow(
selected: selectedUnit == index,
onSelectChanged: (value) {
print(value);
setState(() {
selectedUnit = index;
unitNumber = data[index].unitId;
});
PersistentNavBarNavigator.pushNewScreen(context,
screen: ShowProductDetails(
unitId: data[index].unitId,
));
},
cells: [
DataCell(Text(
data[index].unitId,
style: TextStyle(
color: Constants.matGold,
),
)),
DataCell(Text(
data[index].unitType,
style: TextStyle(
color: Constants.peach,
),
)),
DataCell(Text(
data[index].decription,
style: TextStyle(
color: Constants.appColor,
),
)),
]),
),
),