Добавить DateTime к модели Employee:
class Employee {
int id;
String name;
DateTime dateTime;
Employee(this.id, this.name, this.dateTime);
Map<String, dynamic> toMap() {
final Map<String, dynamic> map = new Map<String, dynamic>();
map['id'] = this.id;
map['name'] = this.name;
map['dateTime'] = dateTime != null ? this.dateTime.toIso8601String() : '';
return map;
}
Employee.fromMap(Map<String, dynamic> map) {
id = map['id'];
name = map['name'];
dateTime = map['dateTime'] != null? DateTime.parse(map['dateTime']): null;
}
}
DateTime.now () возвращает текущий DateTime пользователя. Мы передаем это всякий раз, когда пользователь обновляет или добавляет новые данные. Мы создадим еще один столбец данных и ячейку для отображения времени. Дата и время должны быть преобразованы в представляемую строку, поэтому мы будем использовать нашу пользовательскую функцию getFormattedDate и, наконец, отобразить ее в виджете «Текст».
Future<List<Employee>> employees;
TextEditingController controller = TextEditingController();
String name;
int curUserId;
final formKey = new GlobalKey<FormState>();
var dbHelper;
bool isUpdating;
@override
void initState() {
super.initState();
dbHelper = DBHelper();
isUpdating = false;
refreshList();
}
refreshList() {
setState(() {
employees = dbHelper.getEmployees();
});
}
clearName() {
controller.text = '';
}
validate() {
if (formKey.currentState.validate()) {
formKey.currentState.save();
if (isUpdating) {
Employee e = Employee(curUserId, name,DateTime.now());
dbHelper.update(e);
setState(() {
isUpdating = false;
});
} else {
Employee e = Employee(null, name,DateTime.now());
dbHelper.save(e);
}
clearName();
refreshList();
}
}
form() {
return Form(
key: formKey,
child: Padding(
padding: EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
verticalDirection: VerticalDirection.down,
children: <Widget>[
TextFormField(
controller: controller,
keyboardType: TextInputType.text,
decoration: InputDecoration(labelText: 'Name'),
validator: (val) => val.length == 0 ? 'Enter Name' : null,
onSaved: (val) => name = val,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
FlatButton(
onPressed: validate,
child: Text(isUpdating ? 'UPDATE' : 'ADD'),
),
FlatButton(
onPressed: () {
setState(() {
isUpdating = false;
});
clearName();
},
child: Text('CANCEL'),
)
],
),
],
),
),
);
}
SingleChildScrollView dataTable(List<Employee> employees) {
return SingleChildScrollView(
scrollDirection: Axis.vertical,
child: DataTable(
columns: [
DataColumn(
label: Text('NAME'),
),
DataColumn(
label: Text('DELETE'),
),
DataColumn(
label: Text('DATE'),
),
// DataColumn(label: Text("")'null')
],
rows: employees
.map(
(employee) => DataRow(cells: [
DataCell(
Text(employee.name),
onTap: () {
setState(() {
isUpdating = true;
curUserId = employee.id;
});
controller.text = employee.name;
},
),
DataCell(IconButton(
icon: Icon(Icons.delete),
onPressed: () {
dbHelper.delete(employee.id);
refreshList();
},
)),
DataCell(
Text(((DateTime date) =>
"${date.hour % 12}:${date.minute} ${date.hour > 12
? 'PM'
: 'AM'}")(
employee.dateTime) + ' ${getFormattedDate(employee.dateTime.toIso8601String())}'),
onTap: () {
//Any action
},
),
]),
)
.toList(),
),
);
}
list() {
return Expanded(
child: FutureBuilder(
future: employees,
builder: (context, snapshot) {
if (snapshot.hasData) {
return dataTable(snapshot.data);
}
if (null == snapshot.data || snapshot.data.length == 0) {
return Text("No Data Found");
}
return CircularProgressIndicator();
},
),
);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Stay_Safe'),
centerTitle: true
),
body: new Container(
child: new Column(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
verticalDirection: VerticalDirection.down,
children: <Widget>[
form(),
list(),
],
),
),
);
}
String getFormattedDate(String date) {
var d = DateTime.parse(date);
return [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
][d.month - 1] +
" " + d.day.toString() +
"," +
d.year.toString();
}