Reputation: 6178
I am new to flutter and confused with it's constructor.
For example:
class MyContainer extends StatelessWidget {
final Color color;
const MyContainer({Key key, this.color}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
color: color,
);
}
}
class MyContainer extends StatelessWidget {
final Color color;
MyContainer({this.color});
@override
Widget build(BuildContext context) {
return Container(
color: color,
);
}
}
I removed const
and key
in sample 2, and both of sample1 and sample2 work well.
Is there any potential risk in sample 2?
Upvotes: 2
Views: 863
Reputation: 9135
You can run the code snippet in your local env but first you need to import benchmark_harness
you won't find much of a difference But it will improve the for performance when flutter create widget and elements for the const stateless widget because it won't create element again on rebuild or animations which is memory intensive
void main() {
const ConstObjectBenchMark(32).report();
const NormalObjectBenchmark(32).report();
}
abstract class Benchmark extends BenchmarkBase {
const Benchmark(String name) : super(name);
@override
void exercise() {
for (int i = 0; i < 1000000; i++) {
run();
}
}
}
class ConstObjectBenchMark extends Benchmark {
const ConstObjectBenchMark(this.length) : super('growable[$length]');
final int length;
@override
void run() {
const constPerson = ConstPerson('Const Person', 30);
}
}
class NormalObjectBenchmark extends Benchmark {
const NormalObjectBenchmark(this.length) : super('fixed-length[$length]');
final int length;
@override
void run() {
final normalPerson = NormalPerson('Const Person', 30);
}
}
class ConstPerson {
final String name;
final int age;
const ConstPerson(this.name, this.age);
}
class NormalPerson {
final String name;
final int age;
NormalPerson(this.name, this.age);
}
output:
Upvotes: 0
Reputation: 1619
const
const
keyword is initialized at compile-time
and is already assigned when at runtime
.const
inside a class
. But you can in a
function
.const
can’t be changed during runtime.When to use const?
-
Use const: If you are sure that a value isn’t going to be changed when running your code. For example, when you declare a sentence that always remains the same.
Upvotes: 2
Reputation: 390
when you use const with constructor, it is compile time constant and all values given in constructor must be constant,
try giving unconstant values to const Constuctor to see the difference
Upvotes: 0
Reputation: 780
You would use a const constructor when you dont want this widget to be rebuild. A constant widget is like the constant pi, it won't change. If you have state however you want to use the normal constructor in Sample 2, because the widget changes and cant be constant then.
So you get a slight performance increase when you use const in places where it makes sense (because it wont be rebuild).
The key property is another topic.
Upvotes: 2