I'm trying to create a very simple generator where either "yes", "no", or "maybe" appears inside this (stateless) crystal ball.

enter image description here

This is my code:

import 'dart:html';

import 'package:flutter/material.dart';
import 'dart:math';

void main() => runApp(
      MaterialApp(home: MyApp()),
    );

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: Text('Welcome to Flutter'),
        ),
        body: Center(
          child: Image.asset('images/blu.png'),
        ),
      ),
    );
  }
}

class picker extends StatefulWidget {
  @override
  _pickerState createState() => _pickerState();
}

class _pickerState extends State<picker> {
  List yourList = ["Yes", "No", "Maybe"];
  int randomIndex = Random().nextInt(yourList.length);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: TextButton(
        onPressed: () {
          setState(() {
            print(yourList[randomIndex]);
          });
        },
        child: null,
      ),
    );
  }
}

But it says this error and won't let me hot reload it:

The instance member 'yourList' cant'be accessed in an initializer.

Additionally, I added child:null because that parameter is necessary.

1

There are 1 answers

0
Akif On BEST ANSWER

You need to call yourList in a constructor like this:


class _pickerState extends State<picker> {
  List yourList = ["Yes", "No", "Maybe"];

 int randomIndex;


 _pickerState() {
     randomIndex = Random().nextInt(yourList.length);
  }

...