翩翩从文件中读出Future<String>的实例,而不是文件中的真实文本。

问题描述 投票:0回答:1

我想从FLutter中的一个.txt文件中读取数据,它只包含一个数字。我使用官方文档中的函数(https:/flutter.devdocscookbookpersistencereading-writing-files。),当然对它们进行了一些修改,以适应我的程序。

class _InClassRoomState extends State<InClassRoom> {
  @override
  var pontsz = readpontok().toString();
  void initState() {
    super.initState();

  }
    Future<String> readpontok() async {
  try {
    final file = await _localFile;

    // Read the file.
    String contents = await file.readAsString();

    return await contents;
  } catch (e) {
    // If encountering an error, return 0.
    return null;
  }
}

我的部件树的尊重部分是脚手架的主体。

body: Center(
      child: Text(
        pontsz.toString(),
        textAlign: TextAlign.center,
        style: TextStyle(

          fontSize: 50,
          color: Colors.black,


        ),


      ),

    ),

但当我运行这段代码时,它只写了 "未来的实例在脚手架的主体中。为什么会这样?

string file flutter text future
1个回答
2
投票

你是在给字符串传递一个Future,你应该调用 readpontok()initState() 和setState pontsz = content

class _InClassRoomState extends State<InClassRoom> {

  // create pontsz variable
  var pontsz;

  @override
  void initState() {
    super.initState();
    // call the function
    readpontok();
  }


  Future readpontok() async {
    try {
      final file = await _localFile;

      // Read the file.
      String contents = await file.readAsString();
      setState(() {
        pontsz = contents;
      });
    } catch (e) {
      // If encountering an error, display Error
      setState(() {
        pontsz = "Error";
      });
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.