I found a problem, because I just learned the newest flutter, whereas what I learned was the old version of flutter.
when I make myList variable separate from Children
Errors:
Can't define the 'const' constructor because the field 'mylist' is initialized with a non-constant value.
Try initializing the field to a constant value, or removing the keyword 'const' from the constructor. [Ln 8, Col 3]
Can't define a const constructor for a class with non-final fields.
Try making all of the fields final, or removing the keyword 'const' from the constructor. [Ln 9, Col 9]
Script :
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
List<Widget> mylist = [
Container(
height: 300,
width: 300,
color: Colors.red,
),
Container(
height: 300,
width: 300,
color: Colors.green,
),
Container(
height: 300,
width: 300,
color: Colors.blue,
),
Container(
height: 300,
width: 300,
color: Colors.amber,
),
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("List View"),
),
body: ListView(
//scrollDirection: Axis.horizontal,
children: mylist,
),
),
);
}
}
Please help and explain the details of the problem and references
2
Answers
Remove the
const
keyword sinceMyApp()
isn’t aconst
ant:For an explanation see:
What is the difference between the "const" and "final" keywords in Dart?
Well, because the
mylist
is mutable it means that it can be changed, and re-assignable, and the class which contains it can’t be const anymore.a
const
class is a class whose members are alsoconst
( constant ).so if you’re willing to re-assign the
mylist
value in your code, then you need to remove theconst
keyword from your class constructor like this: