我正在尝试构建一个颤振应用程序,以在特定的硬编码“烘焙”值之间随机选择,并将它们添加到位于卡片中的列表块中。我有三个不在任何类中的变量,这样我就可以在每个小部件和函数中访问它们。然后我尝试在函数中为其分配一个值,但是当我运行该应用程序时,出现错误:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following LateError was thrown building MyHomePage(dirty, state: _MyHomePageState#8da4b):
LateInitializationError: Field 'roast' has not been initialized.
有人知道我能做什么吗?
这是一些代码 -
T getRandomElement<T>(List<T> list) {
final random = new Random();
var i = random.nextInt(list.length);
return list[i];
}
getElement() {
var element = getRandomElement(roastList);
var randRoast = [
roastList[element.id].roast,
];
var randAuthor = [
roastList[element.id].author,
];
var randCategory = [roastList[element.id].category];
roast = randRoast.toString();
author = randAuthor.toString();
category = randCategory.toString();
}
烘烤示例 -
Roast(
10 (id) ,
'roast',
'author of roast',
RoastCategory.category),
我的主页 -
late String roast;
late String author;
late String category;
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Roast'),
centerTitle: true,
backgroundColor: Colors.red,
),
body: Center(
child: Column(
children: [
Card(
child: Row(
children: [
ListTile(
title: Text(roast),
subtitle: Text(author),
)
],
),
),
ElevatedButton(
onPressed: () {
getElement();
},
child: Text('print')),
],
)),
);
}
}