Flutter 从文件 returns Future<String> 实例中读取而不是文件中的真实文本
Flutter reading from file returns Instance of Future<String> instead of the real text in the file
我想从 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;
}
}
我的小部件树的相关部分是脚手架的主体:
body: Center(
child: Text(
pontsz.toString(),
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 50,
color: Colors.black,
),
),
),
但是当我 运行 代码时,它只是在脚手架主体中写入“Instance of Future。为什么?
您正在将 Future 传递给字符串。你应该从 initState()
调用 readpontok()
和 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";
});
}
}
}
我想从 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;
}
}
我的小部件树的相关部分是脚手架的主体:
body: Center(
child: Text(
pontsz.toString(),
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 50,
color: Colors.black,
),
),
),
但是当我 运行 代码时,它只是在脚手架主体中写入“Instance of Future。为什么?
您正在将 Future 传递给字符串。你应该从 initState()
调用 readpontok()
和 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";
});
}
}
}