本文介绍了如何分配未来<>小部件颤动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个 SingleChildScrollView
,它的内容是从一个文件中读取的:
Suppose I have a SingleChildScrollView
, its content is read from a file:
singleChildScrollView(
padding: EdgeInsets.all(8.0),
child: nw Text(
getTextFromFile(), //<---read from file
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 19.0,
),
));
Future<String> getFileData(String path) async {
return await rootBundle.loadString(path);
}
Future<String> getTextFromFile() async {
return getFileData("test.txt");
}
我收到以下错误:
The argument type 'Future<String>' can't be assigned to the parameter
type 'String'.
如何解决问题?
推荐答案
StatefulWidget
可用于此目的.声明一个成员变量 String _textFromFile = ""
;在您的 State 类中,并使用 setState() 更新其在未来解析时的值
方法.
StatefulWidget
can be used for this purpose.Declare a member variable String _textFromFile = ""
; in your State class and update its value on future resolve by using setState()
method.
我从构造函数调用了您的 getTextFromFile()
方法,但您可以从任何地方调用它.
I called your getTextFromFile()
method from the constructor, but you may call it from anywhere.
运行代码:
import 'package:flutter/material.dart';
import 'dart:async';
class StatefullWidgetDemo extends StatefulWidget {
@override
_StatefulWidgetDemoState createState() {
return new _StatefulWidgetDemoState();
}
}
class _StatefulWidgetDemoState extends State<StatefullWidgetDemo> {
String _textFromFile = "";
_StatefulWidgetDemoState() {
getTextFromFile().then((val) => setState(() {
_textFromFile = val;
}));
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Stateful Demo'),
),
body: new SingleChildScrollView(
padding: new EdgeInsets.all(8.0),
child: new Text(
_textFromFile,
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 19.0,
),
),
),
);
}
Future<String> getFileData(String path) async {
return "your data from file";
}
Future<String> getTextFromFile() async {
return await getFileData("test.txt");
}
}
这篇关于如何分配未来<>小部件颤动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!