我有一个小部件(SessionManager),当有新的流对象可用但不重绘时,我希望对其进行重绘,包括其子级。我按下一个按钮来获取下一个问题,如果我遇到一个问题,我应该进入一个新视图,但我不能超越该按钮视图。
class SessionManager extends StatelessWidget{
@override
Widget build(BuildContext context) {
return StreamProvider<Question>.value(
value: QuizzService().questionStream,
child: MaterialApp(
home: Wrapper()
)
);
}
}
class Wrapper extends StatelessWidget{
@override
Widget build(BuildContext context) {
final Question question = Provider.of<Question>(context, listen: true);
if(question != null){
return SingleAnswerWithImage();
}else{
return
RaisedButton(
child: Text("Start question"),
onPressed: () {
QuizzService().getNextQuestion();
},
);
}
}
}
class QuizzService {
StreamController<Question> _questionStreamController = StreamController();
Stream<Question> get questionStream {
return _questionStreamController.stream;
}
void getNextQuestion() {
List<String> answerOptions = ["Hell yes!", "Hell no!", "Why would you even ask me that", "Some answers can be to long as well i guess. This is probably one of them. Unless there is some magic in flutter that autoscales extremly long long texts"];
Question q = new Question("How do you know hello world? " + TimeOfDay.now().toString(), "https://picsum.photos/370/250", answerOptions, "Java - core", QuestionType.SingleAnswerWithImage);
_questionStreamController.add(q);
}
class Question {
String text;
String imageUrl;
List<String> answerOptions;
String tag;
QuestionType type;
Question(this.text, this.imageUrl, this.answerOptions, this.tag, this.type);
}
答案 0 :(得分:0)
我的问题是我在不同的小部件中有多个QuizzService类的实例。因此解决方案是使QuizzService类成为单例。这是我的QuizzService的最终版本
class QuizzService {
StreamController<Question> _questionStreamController = StreamController();
static final QuizzService _singleton = new QuizzService._internal()
Stream<Question> get questionStream {
return _questionStreamController.stream;
}
factory QuizzService() {
return _singleton;
}
QuizzService._internal() {
}
void getNextQuestion() {
List<String> answerOptions = ["Hell yes!", "Hell no!", "Why would you even ask me that", "Some answers can be to long as well i guess. This is probably one of them. Unless there is some magic in flutter that autoscales extremly long long texts"];
Question q = new Question("How do you know hello world? " + TimeOfDay.now().toString(), "https://picsum.photos/370/250", answerOptions, "Java - core", QuestionType.SingleAnswerWithImage);
_questionStreamController.add(q);
}
}