#override of Dart code - dart

I noticed PetitParserDart has a lot of #override in the code, but I don't know how do they be checked?
I tried IDEA dart-plugin for #override, but it has no effect at all. How can we use #override with Dart?

From #override doc :
An annotation used to mark an instance member (method, field, getter or setter) as overriding an inherited class member. Tools can use this annotation to provide a warning if there is no overridden member.
So, it depends on the tool you use.
In the current Dart Editor(r24275), there's no warning for the following code but it should (it looks like a bug).
import 'package:meta/meta.dart';
class A {
m1() {}
}
class B extends A {
#override m1() {} // no warning because A has a m1()
#override m2() {} // tools should display a warning because A has no m2()
}

The #override annotation is an example of metadata. You can use Mirrors to check for these in code. Here is a simple example that checks if the m1() method in the child class has the #override annotation:
import 'package:meta/meta.dart';
import 'dart:mirrors';
class A {
m1() {}
}
class B extends A {
#override m1() {}
}
void main() {
ClassMirror classMirror = reflectClass(B);
MethodMirror methodMirror = classMirror.methods[const Symbol('m1')];
InstanceMirror instanceMirror = methodMirror.metadata.first;
print(instanceMirror.reflectee); // Instance of '_Override#0x2fa0dc31'
}

it's 2021 . the override it's optional
Use the #override annotation judiciously and only for methods where the superclass is not under the programmer's control, the superclass is in a different library or package, and it is not considered stable. In any case, the use of #override is optional. from dart api https://api.dart.dev/stable/2.10.5/dart-core/override-constant.html
example
Class A {
void say (){
print ('Say something 1') ;
}
}
Class B extends A {
#override
void adds() { // when i don't type the same name of super class function show an
// warning not an error say 'The method doesn't override an inherited
// method.' because it's not same name but when type the same name must be
// overriding
print ('Say something 2 ')
}
Update : the main use of #override is when try to reach abstract method inside abstract class in sub class that inherited to the abstract super class . must use #override to access the abstract method .

Related

Dart any differences between with or without abstract keyword?

Hi I just would like to know if there is any difference between giving abstract keyword or not like so.
// with
abstract class A {}
class B extends A {}
// without
class A {}
class B extends A {}
Should I give it?
With abstract you can omit implementations of methods and getters/setters
// with
abstract class A {
int foo();
String get bar;
set baz(String value);
}
var a = A(); // error about instantiating abstract class
class B extends A {
// error about missing implementations
}
var b = B(); // ok
// without
class A {
int foo(); // error about missing implementation
String get bar; // error about missing implementation
set baz(String value); // error about missing implementation
}
class B extends A {}

What does the Object<type> syntax mean in Dart?

In the following code example, from the flutter docs:
class RandomWords extends StatefulWidget {
#override
createState() => RandomWordsState();
}
class RandomWordsState extends State<RandomWords> {
#override
Widget build(BuildContext context) {
final wordPair = WordPair.random();
return Text(wordPair.asPascalCase);
}
}
What exactly does the State<RandomWords> syntax mean?
I understand that you can specify the type for the objects contained in a collection, like lists, using this syntax - List <String>
But I cannot understand the motive behind State<RandomWords>.
Moreover, how can you reference RandomWordsState in RandomWords declaration and also reference RandomWords in RandomWordsState declaration? Shouldn't that cause a circular reference error or something?
I come from dynamically typed languages like python, and this looks a little odd to me, can someone please point me to the right place?
<RandomWords> is a generic type parameter passed to the State class.
The State class looks like
abstract class State<T extends StatefulWidget> extends Diagnosticable {
and RandomWords will be passed to the T type parameter which has a constraint that T needs to be a subclass of StatefulWidget.
State also has a field and getter where the type parameter is used
T get widget => _widget;
T _widget;
This results in a property of the type of the widget
which provides proper autocompletion and type checks in its subclass RandomWordsState
Assume you have
class RandomWords extends StatefulWidget {
RandomWords({this.fixed});
final WordPair fixed;
#override
createState() => RandomWordsState();
}
class RandomWordsState extends State<RandomWords> {
#override
Widget build(BuildContext context) {
// vvvv here we can access `fixed` in a strongly typed manner
final wordPair = widget.fixed ?? WordPair.random();
return Text(wordPair.asPascalCase);
}
}
See also https://www.dartlang.org/guides/language/language-tour#generics

how to split dart class in flutter?

I did the following test, but it doesn't work:
//main.dart
class Test
{
static const a = 10;
final b = 20;
final c = a+1;
}
//part.dart
part of 'main.dart';
class Test
{
final d = a +1; //<---undefined name 'a'
}
I would like to split the class in flutter tutorial into multiple files. For example: _buildSuggestions in a separate file, _buildRow in a separate file, etc.
update:
my solution:
before:
//main.dart
class RandomWordsState extends State<RandomWords> {
{
final _var1;
final _var2;
#override
Widget build(BuildContext context) {
...
body: _buildList(),
);
Widget _buildList() { ... }
Widget _buildRow() { ... }
}
after:
//main.dart
import 'buildlist.dart';
class RandomWordsState extends State<RandomWords> {
{
final var1;
final var2;
#override
Widget build(BuildContext context) {
...
body: buildList(this),
);
}
//buildlist.dart
import 'main.dart';
Widget buildList(RandomWordsState obj) {
... obj.var1 ...
}
I am faced with same problem. My variant based on extensions:
page.dart
part 'section.dart';
class _PageState extends State<Page> {
build(BuildContext context) {
// ...
_buildSection(context);
// ...
}
}
section.dart
part of 'page.dart';
extension Section on _PageState {
_buildSection(BuildContext context) {
// ...
}
}
Dart doesn't support partial classes. part and part of are to split a library into multiple files, not a class.
Private (identifiers starting with _) in Dart is per library which is usually a *.dart file.
main.dart
part 'part.dart';
class Test {
/// When someone tries to create an instance of this class
/// Create an instance of _Test instead
factory Test() = _Test;
/// private constructor that can only be accessed within the same library
Test._();
static const a = 10;
final b = 20;
final c = a+1;
}
part.dart
part of 'main.dart';
class _Test extends Test {
/// private constructor can only be called from within the same library
/// Call the private constructor of the super class
_Test() : super._();
/// static members of other classes need to be prefixed with
/// the class name, even when it is the super class
final d = Test.a +1; //<---undefined name 'a'
}
A similar pattern is used in many code-generation scenarios in Dart like in
https://pub.dartlang.org/packages/built_value
https://pub.dartlang.org/packages/built_redux
https://pub.dartlang.org/packages/json_serializable
and many others.
I just extend it with extension keyword like Swift.
// class_a.dart
class ClassA {}
// class_a+feature_a.dart
import 'class_a.dart';
extension ClassA_FeatureA on ClassA {
String separatedFeatureA() {
// do your job here
}
}
Please ignore the coding conventions, it's just a sample.

Generic ValueConverter

I'm trying to register a custom generic value converter but it's not being picked up in the binding process. What can be wrong. It's based on this manual: https://docs.grails.org/latest/guide/theWebLayer.html#dataBinding
When I remove the generics everything works fine.
my generic enum converter:
abstract class EnumValueConverter < T extends Enum > implements ValueConverter {
#Override
boolean canConvert(Object value) {
value instanceof String
}
#Override
Object convert(Object value) {
try {
T.valueOf(value)
} catch (IllegalArgumentException illegalArgumentException) {
throw new IllegalArgumentException("needs to be one of ${T.values()*.name()} but is: $value")
}
}
#Override
Class<?> getTargetType() {
T
}
}
my specific converter:
class SomeEnumValueConverter extends EnumValueConverter<SomeEnum>{}
registartion in resources.groovy:
someEnumValueConverter SomeEnumValueConverter
You can't use a generic in a context like that. If you create an instance of SomeEnumValueConverter and invoke getTargetType() on that instance the return value will be Object, not SomeEnum so the framework doesn't know what type the converter should be used for.
You can override the getTargetType() method in SomeEnumValueConverter and return SomeEnum.

access to inherited fields in dart

abstract class Painter {
CanvasElement canvas;
Painter(this.canvas);
void draw();
}
class SpritePainter extends Painter{
SpritePainter(this.canvas);
void draw(){
window.console.log("Drawing");
window.console.log(canvas);
}
}
using the above code my application fails when trying to call new SpritePainter(query('#sprite-canvas')); saying that this.canvas is an unknown field. I thought the CanvasElement in the abstract parent class is accessible to the sub class?
Update:
I fixed this with:
SpritePainter(CanvasElement canvas):super(canvas);
but then I read on dart tutorials that abstract classes can only have factory constructors?
You have to forward your param to the super constructor like the following :
abstract class Painter {
CanvasElement canvas;
Painter(this.canvas);
void draw();
}
class SpritePainter extends Painter{
SpritePainter(CanvasElement canvas) : super(canvas);
void draw(){
window.console.log("Drawing");
window.console.log(canvas);
}
}

Resources