Flutter & Python Web-Socket Ft. Socket-IO (Part 3)
Tags: mysql, python, socketio, flutter
Published: 2022-08-07 13:36:00

Welcome back guys,
In the last tutorials, first we learned about how to make a Socket IO server with flask and then we connected our local MySQL database to the server.

Now in this session we are going to use flutter for creating a real time chat application.

So without taking any time.


> Lets Begin

- Create a new project.
- Add following dependencies into **pubspec.yaml** file.

```
socket_io_client: ^2.0.0
shared_preferences: ^2.0.15
```

[socket_io_client](https://pub.dev/packages/socket_io_client):package is used for connecting Flutter application to python server using sockets.

[shared_preferences](https://pub.dev/packages/shared_preferences):This is used for storing roomId and username locally for persistent authentication.


- We are going to follow the following file structure:

![output1](https://imgur.com/Nf6rAHT.png)

- Create a new file called **imports.dart** add followings lines:


![Imports.dart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oan1tvn7bi8v46pdnbxk.png)

[**Raw File**](https://raw.githubusercontent.com/Djsmk123/web_socket_example_flutter/main/lib/imports.dart)


[why do we Exports dart files into one and how we do it?](https://betterprogramming.pub/how-to-export-multiple-dart-files-from-just-one-b2f2964029e)


Note: You will get a lot errors ignore them.


- Again create a new file named **constant.dart** in which we are going add url for web and mobile.

Add these lines of code :


![constant.dart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jztx6wfyr4734pj1zkmn.png)

[**Raw File**](https://raw.githubusercontent.com/Djsmk123/web_socket_example_flutter/main/lib/constant.dart)


- Now we need a stream controller for listening to changes in the database.
so lets create a new file called **"stream_socket.dart"** as


![stream_socket.dart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x1hlt2a9p4cb4vwmbwm2.png)

[**Raw File**](https://raw.githubusercontent.com/Djsmk123/web_socket_example_flutter/main/lib/stream_socket.dart)


- Now replace following lines of codes in **main.dart**
 

![main.dart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3pk1zqqabybiur8ckko7.png)

[**Raw File**](https://raw.githubusercontent.com/Djsmk123/web_socket_example_flutter/main/lib/main.dart)


Lets understand what is happening in  **void initState()** function.

We are calling **init**() Function for getting room_id and username for local storage using **SharedPreferences** library.

If the user name and room id exists in the local database then the user is going to navigate to **ChatScreen** otherwise it will navigate to **LoginScreen**.


as followed by this line:

```
isLoading?const Scaffold(body: Center(child: CircularProgressIndicator(),)):(username!=null && roomId!=null?ChatPage(username: username!, roomId: roomId!):const LogInScreen()));


```


- Now we have to create Login Screen UI just copy paste.


So create a new folder into **lib** folder named **"screens"** and create a new file inside it named "login_screen.dart"






![login1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/guau3537wyd9bz566s93.png)


![login2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iqe5etaf1dwq41vw7mct.png)


![login3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jumlo88ocr5bknbaijic.png)

[**Raw File**](https://raw.githubusercontent.com/Djsmk123/web_socket_example_flutter/main/lib/screens/login_screen.dart)



Just Remember on pressing **"Start Chat"** button we are going to save user_name and room_id into our local storage using "**Shared Preferences**" and user will navigate to 
**"ChatScreen"**.

```
 onTap: () async {
                  final prefs = await SharedPreferences.getInstance();
                  prefs.setString('roomId', roomId!);
                  prefs.setString('username', username!);
                  Navigator.pop(context);
                  Navigator.push(context, MaterialPageRoute(builder: (builder)=>ChatPage(username: username!, roomId: roomId!)));
                },
```



Note:Room_id and user_name will also passed to **ChatScreen** Stateful widget.  

- Same for **chat_screen** just copy paste following lines of code into new file in same folder named **"chat_screen.dart"** and then we will discuss about how **on** and **emit** function working in flutter.



![chat1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rpfnfzxqnbvqgosofsuy.png)


![chat2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sn8gyivrkr0am1s1947h.png)



![chat3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/emw8nyl4246a7xkbrih1.png)

[**Raw File**](https://raw.githubusercontent.com/Djsmk123/web_socket_example_flutter/main/lib/screens/chat_screen.dart)

- Lets Breakdown each part of Chat Screen

in void initState() function we are making connection to server.

``` 
 socket.onConnect((_) {
        // it firing 'join' event so that server can listen the request.
        socket.emit('join', {
          'username':username,
          'roomId':roomId,
        },
        );

      });
```

also we are disposing stream controller in **void dispose()**.

We are using [stream-builder](https://api.flutter.dev/flutter/widgets/StreamBuilder-class.html) for listening message and updating UI continuously.

- Now lets talk about how we are sending new messages.
 
```
// we are firing 'text' event and requesting to the server.
socket.emit('text',{'msg':sentMsg,
                              'room':widget.roomId,
                              'username':widget.username
                            });
```

- and same we are leaving the room using 'left' event.

```
 socket.emit('left',{
                        'username':widget.username,
                        'room':widget.roomId,
                      });

```

and in the last we are clearing preferences.



> Finally Outputs



![output2](https://imgur.com/9QEppAu.png)
![output3](https://imgur.com/ObLKi8Q.png)
![output4](https://imgur.com/OhKihwR.png)



> Our Series of Socket-IO of 3 parts has ended with this.
**_I hope you liked it._**

**_In case You missed part-1 and part-2 read here:_**

Part 1: https://dev.to/djsmk123/flutter-python-web-socket-ft-socket-io-part-1-3icf

Part 2: https://dev.to/djsmk123/flutter-python-web-socket-ft-socket-io-part-2-3oi5

Stay Tuned....

- [**Source Code Backend**](https://github.com/Djsmk123/web_socket_example_backend)

- [**Source Code Client Application**](https://github.com/Djsmk123/web_socket_example_flutter)

> Follow me:

- [GitHub](https://github.com//djsmk123)

- [LinkedIn](https://www.linkedin.com/in/md-mobin-bb928820b)

- [Twitter](https://twitter.com/smk_winner)