因此,我正試圖在其他腳本檔案中顯示我的空白文本。我沒有得到任何錯誤,但我確實得到了一些資訊,而不是顯示的文本。 (閉合。(dynamic) => void from Function "rannn":. Tasks)
有誰能幫助我解決這個問題,使它能顯示文本?
以下是我的代碼
class TaskData extends ChangeNotifier {
List<Task> _tasks = [
Task(name: "Task one")。
任務(name: "任務二")。
任務(名稱:"任務三")。
];
UnmodifiableListView<Task> get tasks {
return UnmodifiableListView(_tasks)。
}
void rannn(String) async {
var randomItem = (_tasks.toList().shuffle()).first.name。
print(randomItem)。
//notifyListeners();。
在此輸入代碼
Widget build(BuildContext context) => Container(
color: Colors.transparent,
孩子。Scaffold(
//backgroundColor: Colors.transparent,/span>
backgroundColor: Colors.blue,
身體。中心(
孩子。Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
//SizedBox(height: 10),
文本(
"${Provider.of<TaskData>(context).rannn}任務"。
),
//SizedBox(height: 10),//puts empty box to space things out。
buildTimer()。
//const SizedBox(height: 10),
buildButtons()。
],
),
),
),
);
非常感謝你!
uj5u.com熱心網友回復:
你做錯了三件事
。第一。void rannn(String)是一個函式,如果你簡單地試圖列印一個函式,你會得到你現在得到的東西。
第二:void rannn(String)是一個無效函式,所以它不會回傳一個Future<String>供你顯示。你應該從中回傳一個字串,就像:
。
Future<String> rann() async {
return (_tasks.toList().shuffle()).first.name。
}
第三:你應該用()來呼叫這個函式,以獲得它的回傳值:
"${Provider.of<TaskData>(context).rannn()} Tasks" ,
問題是,這是一個回傳Future的函式,所以它也不能作業。
解決方案是使用一個FutureBuilder widget,這樣你就可以將Provider.of<TaskData>(context).rannn()傳遞給它的未來引數并等待回傳的未來最終顯示在你的Text widget
例子:
Future<String> rannn() async {
await Future.delayed(const Duration(seconds: 2)); // Just so you can see the Future loading
return (_tasks.toList().shuffle()).first.name。
}
Widget build(BuildContext context) => Container(
color: Colors.transparent,
孩子。Scaffold(
backgroundColor: Colors.blue,
身體。中心(
孩子。Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
FutureBuilder(
未來。Provider.of<TaskData>(context).rannn()。
構建者。(context, snapshot) {
if (! snapshot.hasData) {
return const Text('Loading...') 。
}
return Text('${snapshot.data}') 。
},
),
],
),
),
),
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/313102.html
標籤:
上一篇:屬性'數量'不能被無條件地訪問,因為接收器可以是'null'。試著使訪問有條件(使用'?')。
下一篇:父級小部件沒有使用繼承來更新
