我有一个字符串列表(称为问题)。我基于列表中的当前字符串创建一个文本小部件。我有一个索引int,每按一次按钮它就会增加。我在setState方法中将当前索引增加了1。当当前索引达到字符串列表的长度时,我需要导航到其他页面。否则,我自然会得到RangeError。
setState(() {
this.currentIndex++;
if(this.currentIndex == questions.length) {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => Loser()),
);
}
});
现在,根据上述代码,错误页面出现并迅速消失。它很快被Loser()页面替换。
这是为什么?
在没有显示错误页面的情况下,如何导航到Loser()页面?
编辑:根据要求,错误消息:
════════ Exception caught by widgets library ═══════════════════════════════════
The following RangeError was thrown building LandingPage(dirty, state: _LandingPageState#a8efe):
RangeError (index): Invalid value: Not in inclusive range 0..10: 11
The relevant error-causing widget was
LandingPage
lib/main.dart:21
When the exception was thrown, this was the stack
#0 List.[] (dart:core-patch/growable_array.dart:153:60)
#1 _LandingPageState.build
package:testing_http_package/landing_page.dart:88
#2 StatefulElement.build
package:flutter/…/widgets/framework.dart:4628
#3 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4511
#4 StatefulElement.performRebuild
package:flutter/…/widgets/framework.dart:4684
...
════════════════════════════════════════════════════════════════════════════════
编辑:我认为在导致错误的生成方法中的小部件:
child: Center(
child: Text(
questions[currentIndex], // This line
style: style,
textAlign: TextAlign.center,
),
),
),
在重新运行build方法之前,setState方法是否应该直接进入页面?
编辑:我按照@Nuts建议添加了didChangeDependencies方法,但是它不起作用。现在,仅显示错误页面,而不会继续进入其他页面:
@override
void didChangeDependencies() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if(this.currentIndex == questions.length) {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => Loser()),
);
}
});
super.didChangeDependencies();
}
使用setState-您将在重建整个小部件的同时进行导航。因此,您尝试使用无效的参数重建小部件(在您的情况下为索引)
this.currentIndex++;
if(this.currentIndex => questions.length) {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => Loser()),
);
}
else setState(() {}); // if currentIndex is valid, just rebuild
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句