List< String>为空,但值在重新加载后返回 [英] List<String> empty, but values return after reload

查看:52
本文介绍了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) {
        /* ... */
      },
    );
  }
}

这篇关于List&lt; String&gt;为空,但值在重新加载后返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆