Ported working the Edit Task dialog

This commit is contained in:
Aleksandr Borisenko 2021-06-08 08:50:05 +03:00
parent 74f7756626
commit 21ef483c32
5 changed files with 91 additions and 136 deletions

View File

@ -22,18 +22,20 @@ class ListAPIService extends APIService implements ListService {
@override @override
Future<TaskList> get(int listId) { Future<TaskList> get(int listId) {
/*
return client return client
.get('/lists/$listId') .get('/lists/$listId')
.then((response) => TaskList.fromJson(response.body)); .then((response) => TaskList.fromJson(response.body));
/* */
return client.get('/lists/$listId').then((map) { return client.get('/lists/$listId').then((response) {
final map = response.body;
if (map.containsKey('id')) { if (map.containsKey('id')) {
return client.get("/lists/$listId/tasks").then((tasks) => TaskList.fromJson( return client.get("/lists/$listId/tasks")
map, tasksJson: tasks)); .then((tasks) => TaskList.fromJson(
map, tasksJson: tasks.body));
} }
return TaskList.fromJson(map); return TaskList.fromJson(map);
}); });
*/
} }
@override @override

View File

@ -26,8 +26,8 @@ class Label {
color = json['hex_color'] == '' color = json['hex_color'] == ''
? null ? null
: new Color(int.parse(json['hex_color'], radix: 16) + 0xFF000000), : new Color(int.parse(json['hex_color'], radix: 16) + 0xFF000000),
updated = DateTime.fromMillisecondsSinceEpoch(json['updated']), updated = DateTime.parse(json['updated']),
created = DateTime.fromMillisecondsSinceEpoch(json['created']), created = DateTime.parse(json['created']),
createdBy = User.fromJson(json['created_by']); createdBy = User.fromJson(json['created_by']);
toJSON() => { toJSON() => {

View File

@ -40,16 +40,16 @@ class Task {
title = json['title'], title = json['title'],
description = json['description'], description = json['description'],
done = json['done'], done = json['done'],
reminderDates = (json['reminderDates'] as List<dynamic>) reminderDates = (json['reminder_dates'] as List<dynamic>)
?.map((ts) => dateTimeFromUnixTimestamp(ts)) ?.map((ts) => DateTime.parse(ts))
?.cast<DateTime>() ?.cast<DateTime>()
?.toList(), ?.toList(),
dueDate = dateTimeFromUnixTimestamp(json['dueDate']), dueDate = DateTime.parse(json['due_date']),
startDate = dateTimeFromUnixTimestamp(json['startDate']), startDate = DateTime.parse(json['start_date']),
endDate = dateTimeFromUnixTimestamp(json['endDate']), endDate = DateTime.parse(json['end_date']),
parentTaskId = json['parentTaskID'], parentTaskId = json['parent_task_id'],
priority = json['priority'], priority = json['priority'],
repeatAfter = Duration(seconds: json['repeatAfter']), repeatAfter = Duration(seconds: json['repeat_after']),
labels = (json['labels'] as List<dynamic>) labels = (json['labels'] as List<dynamic>)
?.map((label) => Label.fromJson(label)) ?.map((label) => Label.fromJson(label))
?.cast<Label>() ?.cast<Label>()
@ -58,9 +58,9 @@ class Task {
?.map((subtask) => Task.fromJson(subtask)) ?.map((subtask) => Task.fromJson(subtask))
?.cast<Task>() ?.cast<Task>()
?.toList(), ?.toList(),
updated = dateTimeFromUnixTimestamp(json['updated']), updated = DateTime.parse(json['updated']),
created = dateTimeFromUnixTimestamp(json['created']), created = DateTime.parse(json['created']),
createdBy = User.fromJson(json['createdBy']); createdBy = User.fromJson(json['created_by']);
toJSON() => { toJSON() => {
'id': id, 'id': id,

View File

@ -1,7 +1,6 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:vikunja_app/components/AddDialog.dart'; import 'package:vikunja_app/components/AddDialog.dart';
import 'package:vikunja_app/components/TaskTile.dart'; import 'package:vikunja_app/components/TaskTile.dart';
import 'package:vikunja_app/global.dart'; import 'package:vikunja_app/global.dart';
@ -9,7 +8,6 @@ import 'package:vikunja_app/models/list.dart';
import 'package:vikunja_app/models/task.dart'; import 'package:vikunja_app/models/task.dart';
import 'package:vikunja_app/pages/list/list_edit.dart'; import 'package:vikunja_app/pages/list/list_edit.dart';
import 'package:vikunja_app/pages/list/task_edit.dart'; import 'package:vikunja_app/pages/list/task_edit.dart';
import 'package:vikunja_app/stores/list_store.dart';
class ListPage extends StatefulWidget { class ListPage extends StatefulWidget {
final TaskList taskList; final TaskList taskList;
@ -22,10 +20,8 @@ class ListPage extends StatefulWidget {
class _ListPageState extends State<ListPage> { class _ListPageState extends State<ListPage> {
TaskList _list; TaskList _list;
List<Task> _tasks = [];
List<Task> _loadingTasks = []; List<Task> _loadingTasks = [];
bool _loading = true; bool _loading = true;
int _currentPage = 1;
@override @override
void initState() { void initState() {
@ -48,65 +44,44 @@ class _ListPageState extends State<ListPage> {
var tasks = (_list?.tasks?.map(_buildTile) ?? []).toList(); var tasks = (_list?.tasks?.map(_buildTile) ?? []).toList();
tasks.addAll(_loadingTasks.map(_buildLoadingTile)); tasks.addAll(_loadingTasks.map(_buildLoadingTile));
final taskState = Provider.of<ListProvider>(context);
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text(_list.title), title: Text(_list.title),
actions: <Widget>[ actions: <Widget>[
IconButton( IconButton(
icon: Icon(Icons.edit), icon: Icon(Icons.edit),
onPressed: () => Navigator.push( onPressed: () => Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => ListEditPage( builder: (context) => ListEditPage(
list: _list, list: _list,
)
)
), ),
),
],
),
body: !taskState.isLoading
? RefreshIndicator(
child: taskState.tasks.length > 0
? ListView.builder(
padding: EdgeInsets.symmetric(vertical: 8.0),
// children: ListTile.divideTiles(context: context, tiles: _listTasks()).toList(),
itemBuilder: (context, i) {
if (i.isOdd) return Divider();
final index = i ~/ 2;
// This handles the case if there are no more elements in the list left which can be provided by the api
if (taskState.maxPages == _currentPage &&
index == taskState.tasks.length - 1) return null;
if (index >= taskState.tasks.length &&
_currentPage < taskState.maxPages) {
_currentPage++;
_loadTasksForPage(_currentPage);
}
return index < taskState.tasks.length
? TaskTile(
task: taskState.tasks[index],
)
: null;
})
: Center(child: Text('This list is empty.')),
onRefresh: _loadList,
) )
: Center(child: CircularProgressIndicator()), ),
floatingActionButton: Builder(
builder: (context) => FloatingActionButton(
onPressed: () => _addItemDialog(context), child: Icon(Icons.add),
), ),
)); ],
} ),
body: !this._loading
List<Widget> _listTasks() { ? RefreshIndicator(
var tasks = (_tasks?.map(_buildTile) ?? []).toList(); onRefresh: _loadList,
tasks.addAll(_loadingTasks.map(_buildLoadingTile)); child: _list.tasks.length > 0
return tasks; ? ListView(
padding: EdgeInsets.symmetric(vertical: 8.0),
children: ListTile.divideTiles(
context: context,
tiles: tasks,
).toList(),
)
: Center(child: Text('This list is empty.')),
)
: Center(child: CircularProgressIndicator()),
floatingActionButton: Builder(
builder: (context) => FloatingActionButton(
onPressed: () => _addItemDialog(context),
child: Icon(Icons.add),
),
),
);
} }
TaskTile _buildTile(Task task) { TaskTile _buildTile(Task task) {
@ -127,16 +102,17 @@ class _ListPageState extends State<ListPage> {
.update(Task( .update(Task(
id: task.id, id: task.id,
done: done, done: done,
)) )
.then((newTask) => setState(() { ).then((newTask) => setState(() {
// FIXME: This is ugly. We should use a redux to not have to do these kind of things. // FIXME: This is ugly. We should use a redux to not have to do these kind of things.
// This is enough for now (it works) but we should definitly fix it later. // This is enough for now (it works) but we should definitly fix it later.
_list.tasks.asMap().forEach((i, t) { _list.tasks.asMap().forEach((i, t) {
if (newTask.id == t.id) { if (newTask.id == t.id) {
_list.tasks[i] = newTask; _list.tasks[i] = newTask;
} }
}); });
})); })
);
}, },
); );
} }
@ -145,53 +121,39 @@ class _ListPageState extends State<ListPage> {
return TaskTile( return TaskTile(
task: task, task: task,
loading: true, loading: true,
onEdit: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TaskEditPage(
task: task,
),
),
),
); );
} }
void _loadTasksForPage(int page) {
Provider.of<ListProvider>(context, listen: false).loadTasks(
context: context,
listId: _list.id,
page: page,
);
}
// Future<void> _loadTasksForPage(int page) {
// return VikunjaGlobal.of(context).taskService.getAll(_list.id, {
// "sort_by": ["done", "id"],
// "order_by": ["asc", "desc"],
// "page": [page.toString()]
// }).then((tasks) {
// setState(() {
// _loading = false;
// _tasks.addAll(tasks);
// });
// });
// }
Future<void> _loadList() { Future<void> _loadList() {
return VikunjaGlobal.of(context) return VikunjaGlobal.of(context)
.listService .listService
.get(widget.taskList.id) .get(widget.taskList.id)
.then((list) { .then((list) {
setState(() { setState(() {
_loading = true; _loading = false;
_list = list; _list = list;
}); });
_loadTasksForPage(_currentPage);
}); });
} }
_addItemDialog(BuildContext context) { _addItemDialog(BuildContext context) {
showDialog( showDialog(
context: context, context: context,
builder: (_) => AddDialog( builder: (_) => AddDialog(
onAdd: (title) => _addItem(title, context), onAdd: (name) => _addItem(name, context),
decoration: InputDecoration( decoration: new InputDecoration(
labelText: 'Task Name', labelText: 'Task Name',
hintText: 'eg. Milk', hintText: 'eg. Milk',
), )
), )
); );
} }
@ -207,7 +169,7 @@ class _ListPageState extends State<ListPage> {
setState(() => _loadingTasks.add(newTask)); setState(() => _loadingTasks.add(newTask));
globalState.taskService.add(_list.id, newTask).then((task) { globalState.taskService.add(_list.id, newTask).then((task) {
setState(() { setState(() {
_tasks.add(task); _list.tasks.add(task);
}); });
}).then((_) { }).then((_) {
_loadList(); _loadList();
@ -217,12 +179,4 @@ class _ListPageState extends State<ListPage> {
)); ));
}); });
} }
}
Future<Task> _updateTask(Task task, bool checked) {
// TODO use copyFrom
return VikunjaGlobal.of(context).taskService.update(Task(
id: task.id,
done: checked,
));
}
}

View File

@ -30,14 +30,14 @@ class _TaskEditPageState extends State<TaskEditPage> {
List<Label> _labels; List<Label> _labels;
List<Label> List<Label>
_suggestedLabels; // we use this to find the label object after a user taps on the suggestion, because the typeahead only uses strings, not full objects. _suggestedLabels; // we use this to find the label object after a user taps on the suggestion, because the typeahead only uses strings, not full objects.
var _reminderInputs = new List<Widget>(); var _reminderInputs = <Widget>[];
final _labelTypeAheadController = TextEditingController(); final _labelTypeAheadController = TextEditingController();
@override @override
Widget build(BuildContext ctx) { Widget build(BuildContext ctx) {
// This builds the initial list of reminder inputs only once. // This builds the initial list of reminder inputs only once.
if (_reminderDates == null) { if (_reminderDates == null) {
_reminderDates = widget.task.reminderDates ?? new List(); _reminderDates = widget.task.reminderDates ?? [];
_reminderDates?.asMap()?.forEach((i, time) => _reminderDates?.asMap()?.forEach((i, time) =>
setState(() => _reminderInputs?.add(VikunjaDateTimePicker( setState(() => _reminderInputs?.add(VikunjaDateTimePicker(
@ -48,7 +48,7 @@ class _TaskEditPageState extends State<TaskEditPage> {
} }
if (_labels == null) { if (_labels == null) {
_labels = widget.task.labels ?? new List(); _labels = widget.task.labels ?? [];
} }
return Scaffold( return Scaffold(
@ -59,8 +59,7 @@ class _TaskEditPageState extends State<TaskEditPage> {
builder: (BuildContext context) => SafeArea( builder: (BuildContext context) => SafeArea(
child: Form( child: Form(
key: _formKey, key: _formKey,
child: ListView(padding: const EdgeInsets.all(16.0), children: < child: ListView(padding: const EdgeInsets.all(16.0), children: <Widget>[
Widget>[
Padding( Padding(
padding: EdgeInsets.symmetric(vertical: 10.0), padding: EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField( child: TextFormField(
@ -321,7 +320,7 @@ class _TaskEditPageState extends State<TaskEditPage> {
.update(updatedTask, _labels) .update(updatedTask, _labels)
.catchError((err) { .catchError((err) {
setState(() => _loading = false); setState(() => _loading = false);
Scaffold.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text('Something went wrong: ' + err.toString()), content: Text('Something went wrong: ' + err.toString()),
), ),
@ -330,17 +329,17 @@ class _TaskEditPageState extends State<TaskEditPage> {
VikunjaGlobal.of(context).taskService.update(updatedTask).then((_) { VikunjaGlobal.of(context).taskService.update(updatedTask).then((_) {
setState(() => _loading = false); setState(() => _loading = false);
Scaffold.of(context).showSnackBar(SnackBar( ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('The task was updated successfully!'), content: Text('The task was updated successfully!'),
)); ));
}).catchError((err) { }).catchError((err) {
setState(() => _loading = false); setState(() => _loading = false);
Scaffold.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text('Something went wrong: ' + err.toString()), content: Text('Something went wrong: ' + err.toString()),
action: SnackBarAction( action: SnackBarAction(
label: 'CLOSE', label: 'CLOSE',
onPressed: Scaffold.of(context).hideCurrentSnackBar), onPressed: ScaffoldMessenger.of(context).hideCurrentSnackBar),
), ),
); );
}); });