使用无状态小部件创建简单的随机化器时出错实例成员无法在初始化程序中访问

问题描述

我正在尝试创建一个非常简单的生成器,在该(无状态)水晶球中出现“是”,“否”或“也许”。

enter image description here

这是我的代码

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,);
  }
}

但是它显示了这个错误,不会让我热重装它:

无法在初始化程序中访问实例成员“ yourList”。

此外,我添加了child:null,因为该参数是必需的。

解决方法

您需要像这样在yourList中呼叫constructor


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

 int randomIndex;


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

...