在欢迎页会注入全局的依赖,然后判断是否登录,对应不同的导航:
@override
void onReady() async {
super.onReady();
await GloabConfig.init();
await DenpendencyInjection.init();
LoginProvider loginProvider = Get.find();
print(loginProvider);
// 如果未登录就登录
// 如果已登录就去task页面
if (loginProvider.isLogin()) {
Get.offNamed(Routes.TASK);
} else {
Get.offNamed(Routes.LOGIN);
}
}
}
Task 列表
主页实现了底部导航和嵌入式FloatingActionButtonLocation,没有任务的时候会弹出使用引导。点击加号可以添加任务。因为 api 是分页的,所以也做了分页处理。
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(‘My Task’)),
body: Body(),
floatingActionButton: FloatingActionButton(
onPressed: () {
Get.toNamed(Routes.TASK_ADD);
},
child: Icon(Icons.add),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
bottomNavigationBar: BottomAppBar(
shape: CircularNotchedRectangle(),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
icon: Icon(Icons.calendar_today_sharp),
onPressed: () {
Get.toNamed(Routes.TASK_MOTHLY);
},
),
IconButton(
icon: Icon(Icons.settings),
onPressed: () {
Get.toNamed(Routes.PROFILE);
},
),
],
),
),
);
}
}
任务 item可以点击进入详情和侧滑,有两个侧滑菜单,编辑和删除,对应不同的功能,圆形的checkbox可以完成任务,任务标题和时间在完成时会有删除线。
GetView 就是封装的StatelessWidget,内部有一个 get方法便捷的获取注入的controller,这样连获取的步骤都能省略。
增加和编辑
对应的标题是必须项,描述可以为空,时间是默认当前,优先级有高低中三个,默认是中。
选择日期会弹出日历你,采用局部刷新,提高性能,update([updateDateId])函数的参数是一个 id,只会刷新对应 id 的 GetBuilder,并且 GetX 不受 InheritedWidget的限制,所以可以在任意地方引用未被内存回收的 Controller,所以可以在编辑页面,让列表页也同时刷新。
void handleDatePicker() async {
final datePick = await showDatePicker(
context: Get.context,
firstDate: DateTime(2000),
initialDate: _dateTime,
lastDate: DateTime(2100));
if (datePick != null && datePick != _dateTime) {
_dateTime = datePick;
task.dateStr = _dateTime.format();
dateTimeController.text = task.dateStr;
update([updateDateId]);
}
}
void submit() async {
if (formKey.currentState.validate()) {
formKey.currentState.save();
try {
Get.loading();
await _taskRepository.updateTask(task);
Get.dismiss();
// 刷新列表页
Get.find().update();
// controller.updateTask(task);
Get.back();
} catch (e) {
print(e);
Get.dismiss();
Get.snackbar(‘Error’, e.toString());
}
}
}
月份视图
月份视图用了table_calendar包,这个包功能强大,可以定制日历视图。默认显示两周,点击月份展开四周的月份视图。可以按日期筛选出任务。这里的任务可以点击进入详情和点击checkbox更改状态。
TableCalendar(
onDaySelected: (DateTime day, _, __) {
controller.selectedDate(day);
},
calendarController: controller.calendarController,
startingDayOfWeek: StartingDayOfWeek.monday,
initialCalendarFormat: CalendarFormat.week,
calendarStyle: CalendarStyle(
selectedColor: Theme.of(context).accentColor,
),
)
这里更改状态后,同样可以拿到列表页的Controller去更新列表页:
modifyTaskStatus(Task task) async {
try {
TaskController taskController = Get.find();
await taskController.modifyTaskStatus(task);
} catch (e) {}
update();
}
个人中心
个人中心是一个静态页面,最下面展示了我写的 GetX 的 demo 截图。点击放大的功能放在迭代里做吧。
这里藏有福利,一个漂亮的二次元萌妹子。
扩展函数
在 utils文件夹下写了两个扩展函数,扩展了日期格式化和基于 GetX 的全局加载框。
extension DateExtension on DateTime {
String format() {
return formatDate(this, [
yyyy,
‘-’,
mm,
‘-’,
dd,
]);
}
}
extension GetExtension on GetInterface {
dismiss() {
if (Get.isDialogOpen) {
Get.back();
}
}
loading() {
if (Get.isDialogOpen) {
Get.back();
}
Get.dialog(LoadingDialog());
}
}
使用也很简单,但不要忘了要导入扩展函数类:
dateTime.format();
Get.loading();
。。。。。。
Get.dismiss();
GetService
GetService 我的理解是类似服务,比如 SharedPreferences、Database,还有需要异步初始化的类,放在这里注入非常合适:
TaskDao init() {
TaskDatabase database = TaskDatabase();
return TaskDao(database);
}
}
class AppSpController extends GetxService {
Future init() async {
return await SharedPreferences.getInstance();
}
}
同步的就用同步方法注入:
// 数据库
Get.put(TaskDaoController().init());
异步的用异步方法注入:
// shared_preferences
await Get.putAsync(() => AppSpController().init());
数据库 moor 的使用
Android 通过 room 给开发带来的便利,用过的都知道。moor 就是 Flutter 上的 room。
Moor 使用 Dart 的源代码生成器生成代码,我们可以用函数式的调用操作数据库。这也是需要 moor_generator 依赖项以及 build_runner 的原因。
moor 优点之一是我们可以完全使用 Dart 操作数据库,而不必写数据库语句。这也适用于定义SQL表。创建一个表示 table 的类即可。
class Tasks extends Table {
// 可空类型
IntColumn get completeDate => integer().nullable()();
TextColumn get completeDateStr => text().nullable()();
TextColumn get content => text().nullable()();
// 为空自动生成默认值
IntColumn get date =>
integer().clientDefault(() => DateTime.now().millisecondsSinceEpoch)();
// 为空自动生成默认值
TextColumn get dateStr =>
text().nullable().clientDefault(() => DateTime.now().format())();
// 主键
IntColumn get id => integer().nullable().autoIncrement()();
// 为空自动生成默认值
IntColumn get priority => integer().nullable().withDefault(Constant(0))();
// 为空自动生成默认值
IntColumn get status => integer().nullable().withDefault(Constant(0))();
TextColumn get title => text()();
IntColumn get type => integer().withDefault(Constant(0))();
IntColumn get userId => integer().nullable()();
}
@UseMoor(tables: [Tasks], daos: [TaskDao])
class TaskDatabase extends _$TaskDatabase {
// we tell the database where to store the data with this constructor
TaskDatabase() : super(_openConnection());
// you should bump this number whenever you change or add a table definition. Migrations
// are covered later in this readme.
@override
int get schemaVersion => 1;
}
LazyDatabase _openConnection() {
// the LazyDatabase util lets us find the right location for the file async.
return LazyDatabase(() async {
// put the database file, called db.sqlite here, into the documents folder
// for your app.
final dbFolder = await getApplicationDocumentsDirectory();
final file = File(join(dbFolder.path, ‘db.sqlite’));
return VmDatabase(file);
});
}
数据库操作写在这里也可以,但是会显得臃肿,moor 还提供 Dao ,把操作放在 Dao 类是个好习惯:
@UseDao(tables: [Tasks])
class TaskDao extends DatabaseAccessor with _$TaskDaoMixin {
TaskDao(TaskDatabase db) : super(db);
/// 获取全部
Future<List> get getAllTasks => select(tasks).get();
///imit查询来限制返回的结果数量
///offset偏移量
Future<List> getTasks(int limit, {int offset}) {
return (select(tasks)…limit(limit, offset: offset)).get();
}
///imit查询来限制返回的结果数量
///offset偏移量
Future<List> getTasksWithDateStr(String dateStr) {
return (select(tasks)…where((e) => e.dateStr.equals(dateStr))).get();
}
/// 获取单个数据
/// 没必要用list
Future getTaskById(int id) {
return (select(tasks)…where((t) => t.id.equals(id))).getSingle();
}
Future updateTask(Task entry) {
TasksCompanion();
return update(tasks).replace(entry);
}
Future createOrUpdateUser(String title,
{String content, String date, int type = 0, int priority = 0}) {
return into(tasks).insertOnConflictUpdate(TasksCompanion(
title: Value(title),
content: Value(content),
dateStr: Value(date),
type: Value(type),
priority: Value(priority),
));
}
Future createTask(TasksCompanion task) async {
var id = await into(tasks).insertOnConflictUpdate(task);
return getTaskById(id);
}
/// 批量插入
Future insertMultipleTasks(List entries) async {
await batch((batch) {
batch.insertAll(tasks, entries);
});
}
Future deleteTaskById(int id) {
return (delete(tasks)…where((t) => t.id.equals(id))).go();
}
Future deleteTask(Task entry) {
return delete(tasks).delete(entry);
}
Future modifyStatusByid(int id, int status) async {
// into(tasks).up
Task task = await getTaskById(id);
task.copyWith(
status: status,
);
await updateTask(task);
return task;
}
Future modifyTask(Task task) {
return update(tasks).replace(task);
}
/// 表中数据改变,会发生一个流
Stream<List> watchEntriesInCategory() {
return select(tasks).watch();
}
}
尾声
对于很多初中级Android工程师而言,想要提升技能,往往是自己摸索成长,不成体系的学习效果低效漫长且无助。 整理的这些架构技术希望对Android开发的朋友们有所参考以及少走弯路,本文的重点是你有没有收获与成长,其余的都不重要,希望读者们能谨记这一点。
最后想要拿高薪实现技术提升薪水得到质的飞跃。最快捷的方式,就是有人可以带着你一起分析,这样学习起来最为高效,所以为了大家能够顺利进阶中高级、架构师,我特地为大家准备了一套高手学习的源码和框架视频等精品Android架构师教程,保证你学了以后保证薪资上升一个台阶。
- 思维脑图
- 性能优化学习笔记
- 性能优化视频
当你有了学习线路,学习哪些内容,也知道以后的路怎么走了,理论看多了总要实践的。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门,即可获取!
gory() {
return select(tasks).watch();
}
}
尾声
对于很多初中级Android工程师而言,想要提升技能,往往是自己摸索成长,不成体系的学习效果低效漫长且无助。 整理的这些架构技术希望对Android开发的朋友们有所参考以及少走弯路,本文的重点是你有没有收获与成长,其余的都不重要,希望读者们能谨记这一点。
最后想要拿高薪实现技术提升薪水得到质的飞跃。最快捷的方式,就是有人可以带着你一起分析,这样学习起来最为高效,所以为了大家能够顺利进阶中高级、架构师,我特地为大家准备了一套高手学习的源码和框架视频等精品Android架构师教程,保证你学了以后保证薪资上升一个台阶。
- 思维脑图
[外链图片转存中…(img-S8DwbJka-1715308765782)] - 性能优化学习笔记
[外链图片转存中…(img-wn6nNKu3-1715308765785)]
[外链图片转存中…(img-lfXWpSEo-1715308765787)]
[外链图片转存中…(img-F86A4Nz3-1715308765789)]
[外链图片转存中…(img-v4pc5jEM-1715308765791)]
- 性能优化视频
[外链图片转存中…(img-Nk0yF89u-1715308765793)]
当你有了学习线路,学习哪些内容,也知道以后的路怎么走了,理论看多了总要实践的。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门,即可获取!