'find length of List of String in flutter [duplicate]

    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"



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1