1

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.

4

1 回答 1

1

你需要这样yourList调用constructor


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

 int randomIndex;


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

...
于 2020-10-20T15:37:53.150 回答