【发布时间】:2021-09-16 19:10:37
【问题描述】:
我有以下问题,但无法解决...我正在构建某种问题/答案(是/否)应用程序,并希望实现如果按下按钮(给出答案)按钮保持不变用颜色突出显示。因此,如果用户返回上一个按钮,他可以看到他给出的答案。现在是这样,所有的问题都来自firebase的结构
final CollectionReference _questionsCollectionReference =
FirebaseFirestore.instance
.collection("content")
.doc(content)
.collection("block")
.doc(block)
.collection("questions");
如果用户回答了一个问题,它将被保存在他的用户个人资料中
final firestoreInstance = FirebaseFirestore.instance;
await firestoreInstance
.collection("users")
.doc(user!.id)
.collection("content")
.doc(content)
.collection("block")
.doc(block)
.collection("questions")
.doc(question)
.set({
"answer": answer, //FieldValue.arrayUnion([someData]),
}).then((_) {
print("success!");
});
现在基本上应该是这样,如果用户路径中的答案==“是”,则为“是”按钮着色。 question_view.dart 这里我们使用 PageViewBuilder 构建视图并给它一个 QuestionItem
import 'package:fbapp/ui/shared/ui_helpers.dart';
import 'package:fbapp/ui/widgets/question_item.dart';
import 'package:fbapp/viewmodels/questions_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:stacked/stacked.dart';
class QuestionsView extends StatelessWidget {
final String block;
final String content;
const QuestionsView({Key? key, required this.block, required this.content})
: super(key: key);
@override
Widget build(BuildContext context) {
return ViewModelBuilder<QuestionsViewModel>.reactive(
viewModelBuilder: () => QuestionsViewModel(),
onModelReady: (model) => model.fetchPosts(content, block),
builder: (context, model, child) => Scaffold(
backgroundColor: Colors.white,
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
verticalSpace(35),
Row(
children: <Widget>[
SizedBox(
height: 80,
child: Image.asset('assets/images/logo.png'),
),
],
),
Expanded(
child: model.questions != null
? Center(
child: Container(
width: 700,
height: 450,
child: PageView.builder(
controller: model.getPageController(),
scrollDirection: Axis.vertical,
itemCount: model.questions!.length,
itemBuilder: (context, index) =>
QuestionItem(
question: model.questions![index],
content: content,
block: block,
nextPage: model.nextPage,
saveCurrentUserAnswer:
model.saveCurrentUserAnswer,
getCurrentUserAnswer:
model.getCurrentUserAnswer),
),
),
)
: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(
Theme.of(context).primaryColor),
),
))
],
),
),
));
}
}
question_item.dart
import 'package:fbapp/app/app.locator.dart';
import 'package:fbapp/models/question.dart';
import 'package:flutter/material.dart';
import 'package:stacked_services/stacked_services.dart';
class QuestionItem extends StatelessWidget {
final Question? question;
final String? content;
final String? block;
final String? id;
final void Function()? nextPage;
final Future Function(
String content, String block, String? the question, String answer)?
saveCurrentUserAnswer;
final Future Function(String content, String block, String? question)?
getCurrentUserAnswer;
const QuestionItem(
{Key? key,
this.question,
this.nextPage,
this.saveCurrentUserAnswer,
this.content,
this.block,
this.id,
this.getCurrentUserAnswer})
: super(key: key);
@override
Widget build(BuildContext context) {
return Flex(
direction: Axis.horizontal,
children: [
Expanded(
child: Card(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width * 0.6,
child: ListTile(
leading: Icon(Icons.security),
trailing: IconButton(
icon: Icon(Icons.info),
onPressed: () {
final DialogService _dialogService =
locator<DialogService>();
_dialogService.showDialog(
dialogPlatform: DialogPlatform.Material,
title: "Info",
description: question!.info);
},
),
subtitle: Text("some nice text"),
title: Text(question!.q!),
),
),
const SizedBox(height: 50),
Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
margin: EdgeInsets.all(10),
height: 50.0,
child: SizedBox.fromSize(
size: Size(50, 50), // button width and height
child: ClipOval(
child: Material(
color: "yes" ==
getCurrentUserAnswer!(
content!, block!, question!.id)
.toString()
? Color.fromRGBO(0, 144, 132, 1)
: Colors.grey, // button color
child: InkWell(
splashColor: Color.fromRGBO(0, 144, 132, 1),
// splash color
onTap: () {
nextPage!();
saveCurrentUserAnswer!(
content!, block!, question!.id, "yes");
},
// button pressed
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.thumb_up,
color: Colors.white,
), // icon
Text(
"Yes",
style: TextStyle(
fontSize: 15,
color: Colors.white,
),
), // text
],
),
),
),
),
),
),
const SizedBox(width: 100, height: 100),
Container(
margin: EdgeInsets.all(10),
height: 50.0,
child: SizedBox.fromSize(
size: Size(50, 50), // button width and height
child: ClipOval(
child: Material(
color: "no" ==
getCurrentUserAnswer!(
content!, block!, question!.id)
.toString()
? Color.fromRGBO(0, 144, 132, 1)
: Colors.grey, // button colorr
child: InkWell(
splashColor: Color.fromRGBO(0, 144, 132, 1),
// splash color
onTap: () {
nextPage!();
saveCurrentUserAnswer!(
content!, block!, question!.id, "no");
},
// button pressed
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.thumb_down,
color: Colors.white,
), // icon
Text(
"No",
style: TextStyle(
fontSize: 15,
color: Colors.white,
),
), // text
],
),
),
),
),
),
),
],
)
],
),
),
),
],
);
}
}
这就是我使用“是”和“否”按钮构建页面的方式。 这是 question_view_model.dart,我们在其中引用 firebase 函数来保存和获取答案,如下所示:
...
Future saveCurrentUserAnswer(
String content, String block, String? question, String answer) async {
await _fireStoreService!.saveCurrentUserAnswer(
_authenticationService!.currentUser, content, block, question, answer);
}
Future getCurrentUserAnswer(
String content, String block, String? question) async {
await _fireStoreService!.getCurrentUserAnswer(
_authenticationService!.currentUser, content, block, question);
}
...
以及执行此操作的 firebase 功能:
...
Future saveCurrentUserAnswer(User? user, String content, String block,
String? question, String answer) async {
final firestoreInstance = FirebaseFirestore.instance;
await firestoreInstance
.collection("users")
.doc(user!.id)
.collection("content")
.doc(content)
.collection("block")
.doc(block)
.collection("questions")
.doc(question)
.set({
"answer": answer, //FieldValue.arrayUnion([someData]),
}).then((_) {
print("success!");
});
}
Future<String> getCurrentUserAnswer(
User? user, String content, String block, String? question) async {
String answer = "";
try {
final DocumentReference _answerCollectionReference = FirebaseFirestore
.instance
.collection("users")
.doc(user!.id)
.collection("content")
.doc(content)
.collection("block")
.doc(block)
.collection("questions")
.doc(question);
var answerDocumentSnapshot = await _answerCollectionReference;
await answerDocumentSnapshot.get().then((a) {
if (a.exists) {
answer = a["answer"];
} else {
answer = "";
}
});
print("Answer: $answer");
return answer;
} catch (e) {
return e.toString();
}
}
...
getCurrentUserAnswer 成功打印了答案(总是 2 次,不知道为什么......)
Cont: 00_DSGVO -- Block: b1
2
Answer: no
2
Answer: yes
success!
但按钮永远不会改变颜色。我还尝试了 Stateful 和 setState 以及 Stateless 和 ValueNotifier,但不知何故它不起作用。一个问题是它必须先检查是否有答案,而不是重建 UI(或仅重建按钮),但它是先构建它,然后再检查答案......
【问题讨论】:
-
我认为共享整个文件没有帮助,只共享相关的部分。见how to create a Minimal, Reproducible Example
-
我没有通读整个代码,但这似乎是基本状态管理的典型示例。例如,您可以使用Provider。您可以在共享祖先之上创建一个提供程序,并且下面的所有小部件都可以访问同一实例。如果您对该实例进行更改,则该更改对所有子小部件都可用,即使您更改了页面。
-
你是对的@lenz,但有时很难找到一种中间方法来理解某人想要实现的目标和最小的例子:) 这就是为什么我发布了更多内容以了解复杂性。
标签: firebase flutter flutter-web