Flutter : RangeError (max): Must be positive and <= 2^32: Not in inclusive range 1..4294967296: 0

Viewed 1343

I'm trying to do an app which choose randomly someone. In a page there's some textfields where you put your name in it and a button. When I click on the button it brings me to the result page where I want to display the name of the person randomly chosen. I passed the list of people in the constructor of my result page and made this :

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

I get this error when I the Navigator push the result page:

RangeError (max): Must be positive and <= 2^32: Not in inclusive range 1..4294967296: 0

If you have any idea of what's the problem is and how I could fix it please tell me. Thanks

1 Answers

This error is caused when you pass 0 to _random.nextInt().

So apparently your list is empty and widget.persons.length is returning 0.

Check what's happening with your persons list when you pass it to the widget.

Related