1. Taskly

  • 24.8.8 created
  • 24.8.9 updated

1.1. 创建工程

localhost:flutter chenchangqing$ flutter create taskly
Creating project taskly...
Running "flutter pub get" in taskly...                           2,386ms
Wrote 127 files.

All done!
In order to run your application, type:

  $ cd taskly
  $ flutter run

Your application code is in taskly/lib/main.dart.

1.2. 依赖数据库

1、打开https://pub.dev/,搜索`hive`,点击`hive`
2、复制版本依赖
3、修改.yaml文件,增加hive: "2.2.3"
4、同样的方式依赖hive_flutter: "1.1.0"
5、点击.yaml文件右上角的Pub get获取依赖

1.3. 新增首页

1.3.1. 创建pages/home_page.dart

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
    );
  }
}

1、删除main.dartMyHomePage示例代码
2、MaterialApp的home属性修改为替换为const HomePage()

1.3.2. 新增导航栏

class _HomePageState extends State<HomePage> {
  late double _deviceHeight, _deviceWidth;

  @override
  Widget build(BuildContext context) {
    _deviceHeight = MediaQuery.of(context).size.height;
    _deviceWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: _deviceHeight * 0.15,
        title: const Text(
          "Taskly!",
          style: TextStyle(fontSize: 25),
        ),
      ),
    );
  }
}

1.3.3. 新增列表

  Widget _tasksList() {
    return ListView(
      children: [
        ListTile(
          title: const Text(
            "Do Laundry!",
            style: TextStyle(decoration: TextDecoration.lineThrough),
          ),
          subtitle: Text(DateTime.now().toString()),
          trailing: const Icon(
            Icons.check_box_outlined,
            color: Colors.red,
          ),
        )
      ],
    );
  }

Scaffold中增加body: _tasksList(),

1.3.4. 新增任务按钮

  Widget _addTaskButton() {
    return FloatingActionButton(
      onPressed: () {},
      child: const Icon(Icons.add),
    );
  }

Scaffold中增加floatingActionButton: _addTaskButton(),

1.4. 初始化Hive

1、新建hive_boxes文件夹
2、在main.dart新增runApp(const MyApp());

void main() {
  Hive.initFlutter("hive_boxes");
  runApp(const MyApp());
}

1.5. 新增Task

新增models/task.dart

class Task {
  String content;
  DateTime timestamp;
  bool done;

  Task({required this.content, required this.timestamp, required this.done});

  factory Task.fromMap(Map task) {
    return Task(
        content: task["content"],
        timestamp: task["timestamp"],
        done: task["done"]);
  }

  Map toMap() {
    return {
      "content": content,
      "timestamp": timestamp,
      "done": done,
    };
  }
}

1.6. 任务输入

1、在_HomePageState,新增属性String? _newTaskContent;
2、在_HomePageStatebuild方法新增print("Input Value: $_newTaskContent");
3、新增_displayTaskPopup方法,在onPressed中调用该方法

  _displayTaskPopup() {
    showDialog(
        context: context,
        builder: (BuildContext _context) {
          return AlertDialog(
            title: const Text("Add New Task!"),
            content: TextField(
              onSubmitted: (_value) {},
              onChanged: (_value) {
                _newTaskContent = _value;
              },
            ),
          );
        });
  }

当前效果:

1.7. 使用FutureBuilder

  Widget _tasksView() {
    return FutureBuilder(
        future: Hive.openBox("tasks"),
        builder: (BuildContext _context, AsyncSnapshot _snapshot) {
          if (_snapshot.connectionState == ConnectionState.done) {
            _box = _snapshot.data;
            return _tasksList();
          } else {
            return const Center(child: CircularProgressIndicator());
          }
        });
  }

1.8. 加载动态数据

  Widget _tasksList() {
    List tasks = _box!.values.toList();
    return ListView.builder(
      itemCount: tasks.length,
      itemBuilder: (BuildContext _context, int _index) {
        var task = Task.fromMap(tasks[_index]);
        return ListTile(
          title: Text(
            task.content,
            style: TextStyle(
                decoration: task.done ? TextDecoration.lineThrough : null),
          ),
          subtitle: Text(task.timestamp.toString()),
          trailing: Icon(
            task.done
                ? Icons.check_box_outlined
                : Icons.check_box_outline_blank_outlined,
            color: Colors.red,
          ),
        );
      },
    );
  }

1.9. 增加任务

  _displayTaskPopup() {
    showDialog(
        context: context,
        builder: (BuildContext _context) {
          return AlertDialog(
            title: const Text("Add New Task!"),
            content: TextField(
              onSubmitted: (_value) {
                if (_newTaskContent != null) {
                  var _task = Task(
                      content: _newTaskContent!,
                      timestamp: DateTime.now(),
                      done: false);
                  _box!.add(_task.toMap());
                  setState(() {
                    _newTaskContent = null;
                  });
                }
              },
              onChanged: (_value) {
                setState(() {
                  _newTaskContent = _value;
                });
              },
            ),
          );
        });
  }

1.10. 更新任务

1.11. TODO

1.12. 最终UI

1.13. 源码

https://gitee.com/learnany/flutter/blob/master/taskly.zip

results matching ""

    No results matching ""