-1
    final List<String> quotes = [
        "sentence one",
        "sentence two", 
        "sentence 3",
        "sentence 4",
      ];
    
      final _quetesIndex = Random().nextInt(quotes.length);

When I try to get the quotes.length it gives an error!

"The instance member 'quotes' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression"

smile675
  • 41
  • 3

1 Answers1

0

it's perfectly work in my case no error find. and result is 3 enter image description here

class MyWidget extends StatefulWidget {
 const MyWidget({Key? key}) : super(key: key);

 @override
_MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
 final List<String> quotes = [
    "sentence one",
    "sentence two", 
    "sentence 3",
    "sentence 4",
  ];

@override
Widget build(BuildContext context) {
  final _quetesIndex = Random().nextInt(quotes.length);
  print(_quetesIndex);
 return Container();
 }
}

Result is

enter image description here

Saiful Islam
  • 429
  • 6
  • 11
  • because you're calling inside the main method. Try calling within a class !! – OMi Shah Feb 23 '22 at 06:38
  • oh, is it compulsory to put inside a function ?? but I dont have any place to call the function. is't it possible to get a random quotes inside a class? – smile675 Feb 23 '22 at 06:47