问题描述
我正在尝试创建一个非常简单的生成器,在该(无状态)水晶球中出现“是”,“否”或“也许”。
这是我的代码:
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);
}
...