ITADN

non nullable dataset [] operator

#506Openfsw 创建于 2026-01-13
F
fswcommented
## Issue: In both `JavaScript` and `dart:html` the `dataset` property can be used to check if given `data-*` attribute is set. For example in `dart`: ``` if (div.dataset['someData'] != null) { doSomethingWith(div.dataset['someData']); } ``` In `JS` undefined attribute will return `undefined`. However, currently in `package:web`, `DOMStringMap`'s `operator []` returns non-nullable `String` : ``` extension type DOMStringMap._(JSObject _) implements JSObject { external String operator [](String name); } ``` Because of this, in `package:web`, code like `if (div.dataset['someData'] != null)` will generate an analyzer warning: > The operand can't be 'null', so the condition is always 'true'. And if the data-some-data does not exist it will throw runtime error on execution: > TypeError: null: type 'JSNull' is not a subtype of type 'String' So to achieve above logic in `package:web` I have to do something like: ``` if (div.hasAttribute('data-some-data')) { doSomethingWith(div.dataset['someData']); } ``` Which makes `dataset` less useful and more ugly than dart:html version. I could use `getAttribute` that returns `String?` to do the above but then the dataset becomes not useful at all. Also in current implementation there is no way to delete elements from dataset (JS uses unnamed deleter and delete operator). ## Proposed solution: Simplest solution would be to replace 'String' with 'String?' in 'DOMStringMap' (tested this and it works fine with wasm and dart2js) but if i understand this correctly, this interface is generated from [DOMStringMap](https://developer.mozilla.org/en-US/docs/Web/API/DOMStringMap) [IDL](https://html.spec.whatwg.org/multipage/dom.html#domstringmap) and it seem to match the definition and the issue is we do not have 'undefined'/'null' distinction in Dart? So instead i propose a solution to add `data` wrapper on `dataset` that will handle this issue and allow checking for attribute: ``` if (div.data['someData'] != null) {} ``` This wrapper can also add 'remove' method. I will submit a PR with above in a minute, I am creating this issue to discuss if maybe there is a better solution (maybe modifying the generation process to consider cases like this?).
1 条评论