I am trying to build a flutter application to randomly select between specific hardcoded "roast" values, and to add them to a listtile located in a card. I have three variables that aren't located in any classes, just so I can access them throughout each widget and function. Then I am trying to assign a value to it in a function, but when I run the application, i get the error:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following LateError was thrown building MyHomePage(dirty, state: _MyHomePageState#8da4b):
LateInitializationError: Field 'roast' has not been initialized.
Does anyone know what I can do?
Here is some of the code -
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 example -
Roast(
10 (id) ,
'roast',
'author of roast',
RoastCategory.category),
MyHomePage -
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')),
],
)),
);
}
}