我想从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,
),
),
),
但当我运行这段代码时,它只写了 "未来的实例在脚手架的主体中。为什么会这样?
你是在给字符串传递一个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";
});
}
}
}