List< String>为空,但值在重新加载后返回
我正在尝试从.txt文件中逐行加载不同的值.
I'm trying to load different values from a .txt file line by line.
我正在从资产中加载文件,该文件已在pubspec.yaml中注册.
I'm loading an file from assets, which is already registered in pubspec.yaml.
Future<String> getFileData() async {
return await rootBundle.loadString('assets/files/text.txt');
}
当这返回一个长字符串时,我将其拆分为一个列表:
As this returns one long String I split it into a list:
void doStuff() async {
await getFileData().then((value) => value.split('\n').forEach((element) {
exampleQuestions.add(element);
}));
}
在我的类中调用此方法-构造函数,该构造函数是从Main中通过命名路由调用的:
This method is called in my class - constructor which is called from my Main by a named route:
GameOver.routeName: (context) => GameOver(),
'/game': (context) => Game(
),
},
exampleQuestion获得的内容已填充到doStuff()方法中(已进行了检查),但在_GameState类中失去了它的值,该类要访问该列表的小部件将返回索引不足的异常.
exampleQuestion get's filled in the doStuff() - method (already checked that), but looses it's values in the _GameState class where the widget, that want's to access the list returns an out of index exception.
但是,如果我快速重新加载应用程序,则值设置正确.如果我再单击该按钮以再次继续,则直到我快速重新加载为止,一切都没有改变.
However if i quick reload my application the values are set correctly. If I then click the button to continue again nothing changes until I quick reload.
任何提示都非常感激..
Any hints are very appreciated ..
您不应在小部件构造函数中调用这种异步方法,因为在每次构建时都会调用它们.
You should not call asynchronous methods like this in widget constructors, because they'll be called on every build.
您应该使用带有 FutureBuilder
的 StatefulWidget
.
另一方面,应该使用 LineSplitter
来分割行.
On another note, LineSplitter
should be used for splitting lines.
class _MyWidgetState extends State<MyWidget> {
late final Future<List<String>> _exampleQuestionsFuture;
static Future<String> _getFileData() => rootBundle.loadString('assets/files/text.txt');
@override
void initState() {
super.initState();
_exampleQuestionsFuture = _getFileData().then(const LineSplitter().convert);
}
@override
Widget build(BuildContext context) {
return FutureBuilder<List<String>>(
future: _exampleQuestionsFuture,
builder: (snapshot, data) {
/* ... */
},
);
}
}