Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flutter const constructor error

I was following udacity course on flutter and getting error "the constructor being called isn't a const constructor" on the following line

const _rowHeight = 100.0;
const _cornerRadius = BorderRadius.circular(_rowHeight / 2);// error is on this line
like image 993
Muhammad Touseef Avatar asked Jun 01 '18 18:06

Muhammad Touseef


People also ask

How do I get rid of the constant error in flutter?

lib\main. dart prefer_const_literals_to_create_immutables • 1 fix 1 fix made in 1 file. After this, your all warning message will disappear. In this way, you can ignore the 'Prefer const with constant constructors' warning in specific as well as in all files in Flutter/Dart.

What is a const constructor in flutter?

A const constructor is an optimization! The compiler makes the object immutable, allocating the same portion of memory for all Text('Hi!') objects. But not Text(Math. random()) though, as its value can't be determined at compile time!

How do you remove a prefered const constructor in flutter?

There are several ways to remove this prefer const with constant constructors warning. You can add the ignore line comment at the top of the file. if you want to remove the warning from the file. // ignore_for_file: prefer_const_constructors import 'dart:async'; import 'package:flutter/material.

Why do I have a const flutter?

It is recommended to use const constructors whenever possible when creating Flutter widgets. The reason is the performance increase, since Flutter can save some calculations by understanding that it can reuse that widget from a previous redraw in the current one, since it is a constant value.


2 Answers

This may simply be a bug in border_radius.dart.

BorderRadius.circular is defined as (note that the circular named constructor isn't const):

/// Creates a border radius where all radii are [Radius.circular(radius)].
BorderRadius.circular(double radius) : this.all(
  new Radius.circular(radius),
);

when it seems it could be defined as (though this may break other things):

/// Creates a border radius where all radii are [Radius.circular(radius)].
const BorderRadius.circular(double radius) : this.all(
  const Radius.circular(radius),
);

There's a workaround. Change your code to:

const _rowHeight = 100.0;
const _cornerRadius = BorderRadius.all(Radius.circular(_rowHeight / 2));

Equally, you could remove the const: var _cornerRadius = or BorderRadius cornerRadius =.

like image 97
Richard Heap Avatar answered Nov 02 '22 22:11

Richard Heap


This might be because the widget wrapping _cornerRadius is a const. Try removing it.

like image 1
Mahendra Liya Avatar answered Nov 03 '22 00:11

Mahendra Liya