Compare commits

...

3 Commits

Author SHA1 Message Date
3440713e50 LabWork02 ToDo List is done 2024-09-11 20:13:39 +04:00
3a8b49f9c9 LabWork01 remove the DEBUG banner 2024-09-10 02:00:11 +04:00
e73cee57a3 LabWork01 Done 2024-09-10 01:41:34 +04:00
9 changed files with 456 additions and 111 deletions

116
lib/add_task_dialog.dart Normal file
View File

@ -0,0 +1,116 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'task_provider.dart';
import 'task_model.dart';
import 'package:intl/intl.dart';
class AddTaskDialog extends StatefulWidget {
@override
_AddTaskDialogState createState() => _AddTaskDialogState();
}
class _AddTaskDialogState extends State<AddTaskDialog> {
final _formKey = GlobalKey<FormState>();
String _title = '';
String? _description;
String? _category;
DateTime? _selectedDeadline;
TaskPriority _selectedPriority = TaskPriority.medium;
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text('Add New Task'),
content: Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
decoration: InputDecoration(labelText: 'Task Title*'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a task title';
}
return null;
},
onSaved: (value) {
_title = value ?? '';
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Description (optional)'),
onSaved: (value) {
_description = value;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Category (optional)'),
onSaved: (value) {
_category = value;
},
),
SizedBox(height: 20),
Text('Deadline: ${_selectedDeadline != null ? DateFormat('yMMMd').format(_selectedDeadline!) : 'No deadline'}'),
ElevatedButton(
child: Text('Select Deadline'),
onPressed: () => _selectDeadline(context),
),
DropdownButton<TaskPriority>(
value: _selectedPriority,
onChanged: (TaskPriority? newValue) {
setState(() {
_selectedPriority = newValue!;
});
},
items: TaskPriority.values.map((TaskPriority priority) {
return DropdownMenuItem<TaskPriority>(
value: priority,
child: Text(priority.toString().split('.').last),
);
}).toList(),
),
],
),
),
actions: [
TextButton(
child: Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
ElevatedButton(
child: Text('Add Task'),
onPressed: () {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
Provider.of<TaskProvider>(context, listen: false).addTask(
title: _title,
description: _description,
category: _category,
deadline: _selectedDeadline,
priority: _selectedPriority,
);
Navigator.of(context).pop();
}
},
),
],
);
}
Future<void> _selectDeadline(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime.now(),
lastDate: DateTime(2100),
);
if (picked != null) {
setState(() {
_selectedDeadline = picked;
});
}
}
}

View File

@ -0,0 +1,19 @@
extension DateTimeFormatting on DateTime {
// Форматирует дату как "DD/MM/YYYY"
String toFormattedDate() {
return "${this.day.toString().padLeft(2, '0')}/${this.month.toString().padLeft(2, '0')}/${this.year}";
}
// Форматирует как "x дней осталось"
String toDaysLeft() {
final now = DateTime.now();
final difference = this.difference(now).inDays;
if (difference < 0) {
return "Overdue by ${difference.abs()} days";
} else if (difference == 0) {
return "Due today";
} else {
return "Due in $difference days";
}
}
}

View File

@ -1,125 +1,29 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'task_provider.dart';
import 'task_list_screen.dart';
void main() {
runApp(const MyApp());
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => TaskProvider()),
],
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
title: 'ToDo List',
debugShowCheckedModeBanner: false,
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
home: TaskListScreen(),
);
}
}

View File

@ -0,0 +1,55 @@
import 'package:flutter/material.dart';
import 'task_model.dart';
import 'datetime_extension.dart';
class TaskDetailsScreen extends StatelessWidget {
final Task task;
TaskDetailsScreen({required this.task});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(task.title),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Category: ${task.category ?? 'Not specified'}',
style: TextStyle(fontSize: 16),
),
SizedBox(height: 8),
Text(
'Priority: ${task.priority.name}',
style: TextStyle(fontSize: 16),
),
SizedBox(height: 8),
Text(
'Deadline: ${task.deadline != null ? task.deadline!.toFormattedDate() : 'No deadline'}',
style: TextStyle(fontSize: 16),
),
SizedBox(height: 16),
Text(
'Description:',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
SizedBox(height: 8),
Text(
task.description ?? 'No description available',
style: TextStyle(fontSize: 16),
),
SizedBox(height: 16),
Text(
'Completed: ${task.isCompleted ? "Yes" : "No"}',
style: TextStyle(fontSize: 16),
),
],
),
),
);
}
}

108
lib/task_list_screen.dart Normal file
View File

@ -0,0 +1,108 @@
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'task_provider.dart';
import 'task_details_screen.dart';
import 'add_task_dialog.dart';
import 'task_model.dart';
import 'datetime_extension.dart';
class TaskListScreen extends StatefulWidget {
@override
_TaskListScreenState createState() => _TaskListScreenState();
}
class _TaskListScreenState extends State<TaskListScreen> {
Color _color = Colors.transparent;
@override
void initState() {
super.initState();
Provider.of<TaskProvider>(context, listen: false).loadTasks();
_color =
Color((Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1.0);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: _color,
title: Column(
crossAxisAlignment:
CrossAxisAlignment.start, // Чтобы текст выровнялся по левому краю
children: [
Text('ToDo List',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
Text(
'made by Factorino',
style: TextStyle(
fontSize: 12, // Размер шрифта для подписи
fontStyle: FontStyle.italic, // Сделаем текст курсивом
),
),
],
),
actions: [
IconButton(
icon: Icon(Icons.sort),
onPressed: () {
context.read<TaskProvider>().sortTasks();
},
),
],
),
body: Consumer<TaskProvider>(
builder: (context, taskProvider, child) {
if (taskProvider.tasks.isEmpty) {
return Center(child: Text('No tasks yet.'));
}
return ListView.builder(
itemCount: taskProvider.tasks.length,
itemBuilder: (context, index) {
Task task = taskProvider.tasks[index];
return ListTile(
title: Text(task.title),
subtitle: Text(
'${task.category ?? 'No category'} - ${task.deadline?.toFormattedDate() ?? 'No deadline'}'),
trailing: Checkbox(
value: task.isCompleted,
onChanged: (value) {
context.read<TaskProvider>().toggleTaskCompletion(task);
},
),
onTap: () {
// Открываем экран с деталями задачи
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TaskDetailsScreen(task: task),
),
);
},
onLongPress: () {
context.read<TaskProvider>().removeTask(task);
},
);
},
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () => _openAddTaskDialog(context),
backgroundColor: _color,
child: Icon(Icons.add),
),
);
}
void _openAddTaskDialog(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
return AddTaskDialog();
},
);
}
}

23
lib/task_model.dart Normal file
View File

@ -0,0 +1,23 @@
enum TaskPriority {
low,
medium,
high
}
class Task {
final String title;
final String? description;
final String? category;
final DateTime? deadline;
bool isCompleted;
TaskPriority priority;
Task({
required this.title,
this.description,
this.category,
this.deadline,
this.isCompleted = false,
this.priority = TaskPriority.medium,
});
}

94
lib/task_provider.dart Normal file
View File

@ -0,0 +1,94 @@
import 'package:flutter/material.dart';
import 'task_model.dart';
class TaskProvider with ChangeNotifier {
List<Task> _tasks = <Task>[];
List<Task> get tasks => _tasks;
// Добавление задачи
void addTask({
required String title,
String? description,
String? category,
DateTime? deadline,
TaskPriority priority = TaskPriority.medium,
}) {
final task = Task(
title: title,
description: description,
category: category,
deadline: deadline,
priority: priority,
);
_tasks.add(task);
notifyListeners();
}
// Удаление задачи
void removeTask(Task task) {
_tasks.remove(task);
notifyListeners();
}
// Изменение состояния задачи
void toggleTaskCompletion(Task task) {
task.isCompleted = !task.isCompleted;
notifyListeners();
}
// Сортировка задач по приоритету и дедлайну
void sortTasks() {
_tasks.sort((a, b) {
// Сравнение по приоритету
if (a.priority == b.priority) {
// Если оба дедлайна не null, сравниваем их
if (a.deadline != null && b.deadline != null) {
return a.deadline!.compareTo(b.deadline!);
}
// Если у одной задачи нет дедлайна, она считается "позднее"
if (a.deadline == null) return 1; // Задачи без дедлайна позже
if (b.deadline == null) return -1; // Задачи с дедлайном раньше
return 0;
}
// Сравнение по приоритету
return a.priority.index.compareTo(b.priority.index);
});
notifyListeners();
}
// Метод для завершения всех задач
void completeAllTasks() {
for (var task in _tasks) {
task.isCompleted = true;
}
notifyListeners();
}
// Асинхронная загрузка задач
Future<void> loadTasks() async {
if (_tasks.isEmpty) {
_tasks = [
Task(
title: "Task 1",
category: "Work",
deadline: DateTime.now().add(Duration(days: 1)),
priority: TaskPriority.high),
Task(
title: "Task 2",
category: "Home",
deadline: DateTime.now().add(Duration(days: 2)),
priority: TaskPriority.medium),
Task(
title: "Task 3",
description: "Optional description",
priority: TaskPriority.low),
Task(
title: "Task 4",
category: "Personal",
priority: TaskPriority.high),
];
}
notifyListeners();
}
}

View File

@ -75,6 +75,14 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
intl:
dependency: "direct main"
description:
name: intl
sha256: "910f85bce16fb5c6f614e117efa303e85a1731bb0081edf3604a2ae6e9a3cc91"
url: "https://pub.dev"
source: hosted
version: "0.17.0"
leak_tracker:
dependency: transitive
description:
@ -131,6 +139,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.15.0"
nested:
dependency: transitive
description:
name: nested
sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
path:
dependency: transitive
description:
@ -139,6 +155,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.9.0"
provider:
dependency: "direct main"
description:
name: provider
sha256: c8a055ee5ce3fd98d6fc872478b03823ffdb448699c6ebdbbc71d59b596fd48c
url: "https://pub.dev"
source: hosted
version: "6.1.2"
sky_engine:
dependency: transitive
description: flutter

View File

@ -30,6 +30,8 @@ environment:
dependencies:
flutter:
sdk: flutter
provider: ^6.0.0
intl: ^0.17.0
# The following adds the Cupertino Icons font to your application.