我正在尝试做一个随机选择某人的应用程序。在页面中,有一些文本字段和一个按钮,您可以在其中输入您的姓名。当我单击该按钮时,它会将我带到结果页面,我想在其中显示随机选择的人的姓名。我在结果页面的构造函数中传递了人员列表并制作了这个:
import 'package:flutter/material.dart';
import 'dart:math';
class ResultScreen extends StatefulWidget {
final List persons;
ResultScreen({this.persons});
@override
_ResultScreenState createState() => _ResultScreenState();
}
class _ResultScreenState extends State<ResultScreen> {
final _random = Random();
// var selectedPerson = persons[_random.nextInt(persons.length)];
// print(selectedPerson);
@override
Widget build(BuildContext context) {
return Material(
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("lib/images/fond.jpg"), fit: BoxFit.cover)),
child: Center(
child: Text(' And the loser is\n ${widget.persons[_random.nextInt(widget.persons.length)]} ',
style: TextStyle(color: Colors.black, fontSize: 50, fontWeight: FontWeight.bold),),
),
),
);
}
}
当我导航器推送结果页面时,出现此错误:
RangeError (max): Must be positive and <= 2^32: Not in inclusive range 1..4294967296: 0
如果您知道问题是什么以及如何解决它,请告诉我。谢谢
当您将
0
传递给 _random.nextInt()
时会导致此错误。
所以显然你的列表是空的并且
widget.persons.length
正在返回0
。
当您将人员列表传递到小部件时,检查其发生的情况。
您的人员列表为空。 做这样的事情
列出人员列表 = [ “人物”、“人物2”、“人物3”、“人物4”、“人物5” ];
最终人员 = personList![Random().nextInt(personList!.length)];