相当肯定的是,我只是完全想多了,或者从一个不合逻辑的Angular 来处理它。
我把我的逻辑从我的用户界面中分离出来,按钮按下调用一个位于userModel中的方法,该方法有一个更改通知符(通过一个提供程序传递到MyApp中)。我试图实现firebase,但从未直接从用户界面调用firebase(总是在用户界面代码中有请求,从未使用模型)。
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:tuple/tuple.dart';
//TODO: firebase has been installed now I need to figure out how to implement it
// TODO: add firebase read and write
class UserModel with ChangeNotifier {
//index = session number
List session = [];
//create an instance of firebase (this might need to go higher in the tree)
var db = FirebaseFirestore.instance;
//TODO:
//convert incoming firebase to JSON
//convert outgoing json to firebase
//track session
// takes in current session data and adds the new chunk
// already recorded (new item in list but time, breaks etc. are adding from the last one)
// IF ADDING TO EXISTING, ALL PARAMETRS MUST BE SET
addSessionChunk(
{required String intention,
int workTime = 0,
String progress = "null",
int breakTime = 0}) {
session.add({
"intention": intention,
"workTime": workTime,
"progress": progress,
"breakTime": breakTime,
});
//firebase update?
}
//TODO: when returning to a previous intention, add to the numbers that were
//TODO: currently only works for 1 call per chunk (no going back to the same intention)
//get previous data from this intention for returning to a task (do
//these update functions updadate the LAST CHUNK in the session
updateChunkWorkTime({required int workTime}) {
//this later)
session.last["workTime"] = workTime;
}
//takes in inputed progress and updates the latest chunk with it
updateChunkProgress({required String progress}) {
session.last["progress"] = progress;
}
//takes inputed breaktime and updates the lastest chunk with it
updateChunkBreakTime({required int breakTime}) {
session.last["breakTime"] = breakTime;
}
//returns tuple of the total time spent working and breaking in the current session
calculateSessionTimeTotal() {
int totalWorkTime = 0;
int totalBreakTime = 0;
for (var chunk in session) {
totalWorkTime += chunk["workTime"] as int;
totalBreakTime += chunk["breakTime"] as int;
}
return Tuple2(totalWorkTime, totalBreakTime);
}
//firebase functions
pushDataUp() {
db.collection("sessions").doc().set({
"currentSession": session,
"total": calculateSessionTimeTotal().toString()
});
}
pullDataDown() {}
}
你可以在底部看到,我开始尝试并想出了一种方法来同步本地数据状态与firebase,但我感到困惑,似乎奇怪的是,用户发送他们的数据到firebase,然后回到模型,已经持有的数据?
本地模型和云数据库交互的最佳方法是什么?任何正确方向的指导都非常感谢。
1条答案
按热度按时间rryofs0p1#
你可能会觉得奇怪的是,实际上command query responsibility segregation是一个定义良好的模式,也是大多数现代UI框架背后的基本模式。通过将命令(在这里写入数据)与查询(在这里阅读数据)分离,每个操作都变得更简单,整个应用程序变得更容易推理。
在Firestore处于Flutter模式时,这通常会转化为:
1.用户采取一些操作。
1.您的代码将写入数据库。
onSnapshot
侦听器将被更新的数据触发。1.代码使用新数据更新数据模型/状态。
1.然后呈现更新的UI。
所有这一切都发生得非常快,因为Firebase实际上在将数据发送到服务器之前就在本地处理它,并处理与服务器同步期间可能发生的任何异常。