我正在尝试创建一个非常简单的生成器,在此(无状态) Crystal 球中出现"is",“否”或“也许”。
这是我的代码:
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);
}
...
关于flutter - 使用无状态小部件创建简单的随机化器时出错。实例成员无法在初始化程序中访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64448247/