gpt4 book ai didi

firebase - 我正在尝试使用 Provider 和 Firebase 流式传输模型列表,并将字段值设置为我应用程序中的另一个模型

转载 作者:行者123 更新时间:2023-12-04 17:19:53 25 4
gpt4 key购买 nike

我正在使用 Flutter、Provider 和 Firebase 构建一个生产力应用程序。我目前有许多流,我从 Firestore 中收集这些流并将它们转换为模型列表。我遇到了一个问题,当我尝试创建任务模型列表时,我返回了一个空列表。在 Firestore 中,我有一个任务、状态和项目的集合。我想将 task.project 值设置为等于项目集合中关联的 Project 模型。主 Dart :

void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(ProductivityApp());
}

class ProductivityApp extends StatefulWidget {
@override
_ProductivityAppState createState() => _ProductivityAppState();
}

class _ProductivityAppState extends State<ProductivityApp> {
bool _initialized = false;
bool _error = false;

void initializeFlutterFire() async {
try {
await Firebase.initializeApp();
setState(() {
_initialized = true;
});
} catch (e) {
_error = true;
}
}

@override
void initState() {
initializeFlutterFire();
super.initState();
}

@override
Widget build(BuildContext context) {
if (_error) {
return Center(child: Text('Something went wrong'));
}
if (!_initialized) {
return Center(child: Text('Loading'));
}
return StreamProvider<User>.value(
value: AuthService().user,
child: MultiProvider( // TODO: fix the issue for user to be logged in for the first time
providers: [
StreamProvider<List<Project>>.value(value: ProjectService().streamProjects()),
StreamProvider<List<Task>>.value(value: TaskService().streamTasks(context)),
StreamProvider<List<Status>>.value(value: StatusService().streamStatuses())
],
child: MaterialApp(
title: 'ProductivityApp',
theme: appTheme(),
// home: Wrapper(),
// routes: routes,
onGenerateRoute: generateRoute,
initialRoute: '/',
),
),

);
}
}

任务流:

// Snapshot Conversion to Task Model and Stream
Stream<List<Task>> streamTasks(BuildContext context) {
var ref = _getTaskReference();
return ref.snapshots().map((querySnapshot) => querySnapshot.docs
.map((queryDocument) => Task.fromFirestore(queryDocument, context))
.toList());
}

任务模型:

class Task {
String taskID = '';
String taskName = 'Default Name';
Project project = Project();
Status status = Status();
int taskTime = 0;
DateTime dueDate = DateTime(1);
DateTime createDate = DateTime.now();
// List<String> subtasks = [];

Task(
{this.taskID,
this.taskName,
this.project,
this.status,
this.taskTime,
this.dueDate,
this.createDate});



factory Task.fromFirestore(DocumentSnapshot snapshot, BuildContext context) {
List<Project> projects = Provider.of<List<Project>>(context);
List<Status> statuses = Provider.of<List<Status>>(context);
Map data = snapshot.data();
Project associatedProject = projects
.firstWhere((project) => project.projectName == data['pojectName']);
print(associatedProject);
Status status = statuses
.firstWhere((status) => status.statusName == data['statusName']);
return Task(
taskID: snapshot.id ?? '',
taskName: data['taskName'].toString() ?? '',
project: associatedProject ?? Project(),
status: status ?? Status(),
taskTime: data['taskTime'] ?? 0,
dueDate:
DateTimeFunctions().timeStampToDateTime(date: data['dueDate']) ??
DateTime.now(),
createDate:
DateTimeFunctions().timeStampToDateTime(date: data['createDate']) ??
DateTime.now());
}
}

感谢您的帮助!

最佳答案

我终于找到了解决问题的方法!我使用了许多不同的资源并将它们组合在一起以获得一个工作模型。

首先,我实现了一个基于此 answer 的用户信息重建的 Auth_widget_builder .这实际上解决了先前留待稍后修复的问题。通过使用这种方法,我能够根据用户重建 Material Design 之上的身份验证小部件,我需要访问我的用户集合中正确的 firestore 文档。

主.dart

@override
Widget build(BuildContext context) {
if (_error) {
return Center(child: Text('Something went wrong'));
}
if (!_initialized) {
return Center(child: Text('Loading'));
}
return Provider(
create: (context) => AuthService(),
child: AuthWidgetBuilder(builder: (context, userSnapshot) {
return MaterialApp(
title: 'Productivity App',
theme: appTheme(),
home: AuthWidget(userSnapshot: userSnapshot),
// onGenerateRoute: generateRoute,
// initialRoute: '/',
);
}),
);
}
}

其次,在 Auth_widget_builder 中我嵌套了两个 MultiProvider。第一个创建的提供者将产生我的服务类。然后我添加了 builder: function based on this answer ,它返回了第二个包含我的 StreamProvider 的 MultiProvider。这是可行的,因为 builder: 函数重建了 BuildContext,这样我就可以访问其他 Provider 中的对象以保存为另一个对象中的字段。

auth_widget_builder.dart

/// Used to create user-dependant objects that need to be accessible by all widgets.
/// This widget should live above the [MaterialApp].
/// See [AuthWidget], a descendant widget that consumes the snapshot generated by this builder.

class AuthWidgetBuilder extends StatelessWidget {
const AuthWidgetBuilder({Key key, @required this.builder}) : super(key: key);
final Widget Function(BuildContext, AsyncSnapshot<UserModel>) builder;

@override
Widget build(BuildContext context) {
print('AuthWidgetBuilder rebuild');
final authService = Provider.of<AuthService>(context, listen: false);
return StreamBuilder<UserModel>(
stream: authService.onAuthStateChanged,
builder: (context, snapshot) {
print('StreamBuilder: ${snapshot.connectionState}');
final UserModel user = snapshot.data;
if (user != null) {
return MultiProvider(
providers: [
Provider<UserModel>.value(value: user),
Provider(create: (context) => ProjectService()),
Provider(create: (context) => StatusService()),
Provider(create: (context) => TaskService()),
Provider(create: (context) => TimeService()),
],
builder: (context, child) {
return MultiProvider(
providers: [
StreamProvider<List<Project>>.value(
value: Provider.of<ProjectService>(context)
.streamProjects()),
StreamProvider<List<Status>>.value(
value: Provider.of<StatusService>(context)
.streamStatuses()),
StreamProvider<List<Task>>.value(
value: Provider.of<TaskService>(context)
.streamTasks(context)),
StreamProvider<List<TimeEntry>>.value(
value: Provider.of<TimeService>(context)
.streamTimeEntries(context))
],
child: builder(context, snapshot),
);
},
child: builder(context, snapshot),
);
}
return builder(context, snapshot);
},
);
}
}

第三,我更新了服务类以查找适当的对象并将其传递给模型。

tasks_data.dart

// Snapshot Conversion to Task Model and Stream
Stream<List<Task>> streamTasks(BuildContext context) {
CollectionReference ref = _getTaskReference();
List<Project> projects;
getProjects(context).then((projectList) => projects = projectList);
List<Status> statuses;
getStatuses(context).then((statusList) => statuses = statusList);
return ref.snapshots().map((QuerySnapshot querySnapshot) =>
querySnapshot.docs.map((QueryDocumentSnapshot queryDocument) {
Project project = projects[projects.indexWhere((project) =>
project.projectName ==
queryDocument.data()['projectName'].toString())];
Status status = statuses[statuses.indexWhere((status) =>
status.statusName == queryDocument.data()['status'].toString())];
return Task.fromFirestore(queryDocument, project, status);
}).toList());
}

Future<List<Project>> getProjects(BuildContext context) async {
List<Project> projects =
await Provider.of<ProjectService>(context).streamProjects().first;
return projects;
}

Future<List<Status>> getStatuses(BuildContext context) async {
List<Status> statuses =
await Provider.of<StatusService>(context).streamStatuses().first;
return statuses;
}

关于此实现的最好的部分是它全部发生在 Material Widget 之上,这意味着我可以使用正常范围之外的小部件(如 Navigator.push())访问它。希望这适用于任何需要类似解决方案的人。

关于firebase - 我正在尝试使用 Provider 和 Firebase 流式传输模型列表,并将字段值设置为我应用程序中的另一个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66857337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com