How to listen to changes from php MySQL server with web_socket_channel in flutter

3,243

You need to have WebSocket server. If you need to ensure your code is working, use this server provided in the doc(http://www.websocket.org/echo.html)

Connect to a test server provided by websocket.org. The server sends back the same message you send to it. This recipe uses the following steps:

  • Connect to a WebSocket server
  • Listen for messages from the server
  • Send data to the server
  • Close the WebSocket connection

Demo that you can use(this is available in flutter cookbook)

import 'package:flutter/foundation.dart';
import 'package:web_socket_channel/io.dart';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final title = 'WebSocket Demo';
    return MaterialApp(
      title: title,
      home: MyHomePage(
        title: title,
        channel: IOWebSocketChannel.connect('ws://echo.websocket.org'),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;
  final WebSocketChannel channel;

  MyHomePage({Key key, @required this.title, @required this.channel})
      : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Form(
              child: TextFormField(
                controller: _controller,
                decoration: InputDecoration(labelText: 'Send a message'),
              ),
            ),
            StreamBuilder(
              stream: widget.channel.stream,
              builder: (context, snapshot) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 24.0),
                  child: Text(snapshot.hasData ? '${snapshot.data}' : ''),
                );
              },
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _sendMessage,
        tooltip: 'Send message',
        child: Icon(Icons.send),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  void _sendMessage() {
    if (_controller.text.isNotEmpty) {
      widget.channel.sink.add(_controller.text);
    }
  }

  @override
  void dispose() {
    widget.channel.sink.close();
    super.dispose();
  }
}

These all details are available here with sample code.

If your server is not websoket server, these may helpful:

How to create websockets server in PHP

https://www.twilio.com/blog/create-php-websocket-server-build-real-time-even-driven-application

Share:
3,243
Norbert
Author by

Norbert

I am a passionate software developer who develops desktop,web and mobile(android&amp;iOS with Flutter) software I am familiar with the following Dart Flutter Nodejs Reactjs Php mySQL Python html css

Updated on December 16, 2022

Comments

  • Norbert
    Norbert over 1 year

    I am trying to get data from an API endpoint into my flutter app. I can do this with http request but I want to receive the changes any time there is an update do the database. I found out this can be done with web_socket_channel.

    So far I have tried

    final WebSocketChannel channel = IOWebSocketChannel.connect("ws://127.0.0.1:3306/codeishweb/getData.php");
    
    // In the StreamBuilder
    
    StreamBuilder(
    strema: channel.stream,
    builder:(context, snapshot){
    return Center(child:Text(snapshot.hasData? snapshot.data: "nothing available"));
    }
    );
    

    This doesn't work and I also get an error that Unsupported operation: Platform._version.

    How can I produce what I want to achieve. Thanks in advance.