Skip to content

Commit

Permalink
Convert grpc-web example to package:web
Browse files Browse the repository at this point in the history
  • Loading branch information
aran committed Dec 16, 2024
1 parent 93909b7 commit 2b2b151
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 14 deletions.
27 changes: 18 additions & 9 deletions example/grpc-web/lib/app.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@
// limitations under the License.

import 'dart:async';
import 'dart:html';

import 'package:web/web.dart';
import 'src/generated/echo.pbgrpc.dart';

class EchoApp {
Expand Down Expand Up @@ -56,13 +55,23 @@ class EchoApp {
}

void _addMessage(String message, String cssClass) {
final classes = cssClass.split(' ');
querySelector('#first')!.after(DivElement()
..classes.add('row')
..append(Element.tag('h2')
..append(SpanElement()
..classes.add('label')
..classes.addAll(classes)
document.querySelector('#first')!.after(HTMLDivElement()
..classList.add('row')
..append(HTMLHeadingElement.h2()
..append(HTMLSpanElement()
..classList.add('label')
..classList.addAll(cssClass)
..text = message)));
}
}

// The documentation of DOMTokenList.add implies it can handle multiple classes,
// but in Chrome at least it does not.
extension AddAll on DOMTokenList {
void addAll(String cssClass) {
final classes = cssClass.split(' ');
for (final c in classes) {
add(c);
}
}
}
1 change: 1 addition & 0 deletions example/grpc-web/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ dependencies:
grpc:
path: ../../
protobuf: ^3.0.0
web: ^1.1.0

dev_dependencies:
build_runner: ^2.0.0
Expand Down
9 changes: 4 additions & 5 deletions example/grpc-web/web/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,20 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'dart:html';

import 'package:grpc/grpc_web.dart';
import 'package:grpc_web/app.dart';
import 'package:grpc_web/src/generated/echo.pbgrpc.dart';
import 'package:web/web.dart';

void main() {
final channel = GrpcWebClientChannel.xhr(Uri.parse('http://localhost:8080'));
final service = EchoServiceClient(channel);
final app = EchoApp(service);

final button = querySelector('#send') as ButtonElement;
final button = document.querySelector('#send') as HTMLButtonElement;
button.onClick.listen((e) async {
final msg = querySelector('#msg') as TextInputElement;
final value = msg.value!.trim();
final msg = document.querySelector('#msg') as HTMLInputElement;
final value = msg.value.trim();
msg.value = '';

if (value.isEmpty) return;
Expand Down

0 comments on commit 2b2b151

Please sign in to comment.