Search code examples
dartdart-async

Client-side, then() or other?


How i can use "Future" in client-side ?

And, how I can block the execution of my code, while no event is catch ?

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

Map data;

Future<String> ft_get_pseudo()
{
  InputElement button;
  InputElement text;

  text = querySelector('[name="pseudo"]');
  button = querySelector('[name="push"]');
  button.onClick.listen((_) => text.value);
}

void    main()
{
    WebSocket wss;
  String encode;

  data = new Map();
    wss = new WebSocket('ws://127.0.0.1:4040/ws');
  ft_get_pseudo().then((name)
  {
    data['pseudo'] = name;
    encode = JSON.encode(data);
    wss.onOpen.listen((_) => wss.send(encode));
    wss.onMessage.listen((msg) => print("Msg received : ${msg.data}"));
  });
}

I saw Promise function in ecmascript 6, there is a way to use it, or the idea ?

HTML :

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <script type="application/dart" src="client.dart"></script>
    <link rel="stylesheet" href="style.css" type="text/css">
    <title>Client</title>
</head>
<body>
<div id="console">
</div>
<input type="text" name="pseudo" size="20" placeholder="pseudo">
<input type="button" name="push" value="Send">
</body>
</html>

Solution

  • I think you want to do something like this, but I don't yet fully understand what you try to accomplish. Can you please just add a comment what you need differently?

    Map data;
    
    void main() {
      //(querySelector('[name="push"]') as ButtonInputElement).onClick.listen(btnClickHandler);
      (querySelector('[name="push"]') as ButtonInputElement).onClick.first.then(btnClickHandler);
    
      // this would work too, because every element has the click event.
      // querySelector('[name="push"]').onClick.listen(btnClickHandler);
    }
    
    void btnClickHandler(MouseEvent e) {
      String name = (querySelector('[name="pseudo"]') as TextInputElement).value;    
    
      data = {'pseudo': name}; 
      String encode = JSON.encode(data);
    
      WebSocket wss = new WebSocket('ws://127.0.0.1:4040/ws');
      wss.onOpen.listen((_) => wss.send(encode));
      wss.onMessage.listen((msg) => print("Msg received : ${msg.data}"));
    }