After the server pushes data to the client in flutter websocket, many people actually handle it if / switch; I feel that this way of writing is not very good!
One way I thought of:
Create two files and sums in a new socket directory under the lib directory;
: Mainly controls the connection, disconnection and processing of received messages;
Then route the messages returned by the websocket server;
import 'package:lee/logic/'; typedef void RouteHandle(Map params); var wsRouter = new WsRouter(); class WsRouter { static Map<String, RouteHandle> _routers = new Map(); init() { ((route) { ((name, value) { (name, value); }); }); } // Add routing void add(String name, RouteHandle handle) { WsRouter._routers[name] = handle; } //Routing processing Future<void> handle(String name, Map params) async { RouteHandle handle = WsRouter._routers[name]; if (handle == null) { print("Route does not exist"); return; } handle(params); } } List<Map<String, RouteHandle>> routers = [ {"login": }, {"kick": }, ];
import 'package:lee/socket/'; import 'package:web_socket_channel/'; import 'dart:convert'; var webSocket = new WebSocket(); class WebSocket { // webSocket connection IOWebSocketChannel webSocketChannel; factory WebSocket() => _webSocket(); static WebSocket _instance; // Constructor WebSocket._() { // Initialize webSocket routing (); } static WebSocket _webSocket() { if (_instance == null) { _instance = WebSocket._(); } return _instance; } conn() { IOWebSocketChannel channel = new ( "ws://127.0.0.1:8080/ws", pingInterval: Duration(milliseconds: 100)); .listen((data) => onMessage(data), onError: onError, onDone: onDone); = channel; } onMessage(response) async { // For example, the server returns a json probably like this // {"cmd":"kick","data":{}} // {"cmd":"login","data":{}} Map params = (response); (params["cmd"], params["data"]); } onError(err) async {} onDone() async {} }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.