如何用 flutter 制作 mysql 实时数据库?

How to make a mysql realtime database with flutter?

我正在开发这个聊天应用程序,我显然不知道该怎么做,但我掌握了一些基础知识,比如我在我的应用程序和 mysql 数据库之间建立了连接并获取数据,但我认为我需要使数据库成为实时数据库,我又不知道该怎么做,这对这部分有什么帮助吗? 也是 flutter 的新手 :)

https://flutter.dev/docs/cookbook/networking/web-sockets 使用本教程。还要研究套接字的概念。请记住,在制作聊天应用程序时,您还应该考虑隐私和安全。

  1. Connect to a WebSocket server.

    The web_socket_channel package provides the tools you need to connect to a WebSocket server. The package provides a WebSocketChannel that allows you to both listen for messages from the server and push messages to the server.

    In Flutter, use the following line to create a WebSocketChannel that connects to a server:

    final channel = WebSocketChannel.connect(
      Uri.parse('wss://echo.websocket.org'),
    );
    
  2. Listen for messages from the server.

    Now that you've established a connection, listen to messages from the server. After sending a message to the test server, it sends the same message back. In this example, use a StreamBuilder widget to listen for new messages, and a Text widget to display them.

    StreamBuilder(
      stream: channel.stream,
      builder: (context, snapshot) {
        return Text(snapshot.hasData ? '${snapshot.data}' : '');
      },    
    )
    
  3. Send data to the server.

    To send data to the server, add() messages to the sink provided by the WebSocketChannel.

    channel.sink.add('Hello!');
    
  4. Close the WebSocket connection.

    After you're done using the WebSocket, close the connection:

    channel.sink.close();
    

查看Askless,它简化了使用任何数据库创建实时 Flutter 应用程序

我开发这个包的目的是简化 websocket 的使用。如果客户端失去连接,库将自动重新发送数据到服务器,并且 it has other benefits. The Askless server side 需要编码在 JavaScript/TypeScript.

Flutter 客户端将能够使用 MySQL 或其他数据库收听实时更新,例如:

//other widgets...

AsklessClient.instance
    .listenAndBuild(
      route: 'allProducts',
      builder: (context,  snapshot) {
          if(!snapshot.hasData)
             return Container();

          final listOfProductsNames =
              (snapshot.data as List)
              .map((product) => Text(product['name'])).toList();

          return Column(
             children: listOfProductsNames,
          );
      }
    ),

//other widgets...

它还有一个 JavaScript/TypeScript 可以与 Flutter 配对的客户端支持,例如,如果您的 App 有一个使用 React 或其他 SPA 框架的 Web 版本。