0

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')),
        ],
      )),
    );
  }
}
bigman1234
  • 105
  • 2
  • 12
  • `roast` is not initialized until `onPressed()` is triggered, but your widget tree unconditionally tries to construct `Text(roast)`. Either make `roast` nullable and check if it's `null` before using it, or initialize it to a non-null default value. – jamesdlin Jun 20 '21 at 09:53
  • Would I only have to do the for roast? Because I also reference author in the subtitle of the list tile.... – bigman1234 Jun 20 '21 at 11:14
  • Yes, you would need to do that for `author` too. Use `late` only for variables that you promise will be initialized before they're used. – jamesdlin Jun 20 '21 at 18:48

0 Answers0