【问题标题】:Flutter reading from file returns Instance of Future<String> instead of the real text in the file从文件中读取的 Flutter 返回 Future<String> 的实例,而不是文件中的真实文本
【发布时间】:2020-06-04 13:09:26
【问题描述】:

我想从 FLutter 中的 .txt 文件中读取数据,它只包含一个数字。我使用官方文档中的函数(https://flutter.dev/docs/cookbook/persistence/reading-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;
  }
}

我的小部件树的相关部分是 Scaffold 的主体:

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

          fontSize: 50,
          color: Colors.black,


        ),


      ),

    ),

但是当我运行代码时,它只是在脚手架的主体中写入“Future 的实例。为什么?

【问题讨论】:

    标签: string file flutter text future


    【解决方案1】:

    您正在将 Future 传递给字符串。你应该从initState()和setStatepontsz = content调用readpontok()

    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";
          });
        }
      }
    }
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多