DEV Community

Cover image for Flutter & Python Web-Socket Ft. Socket-IO (Part 3)
Md. Mobin
Md. Mobin

Posted on • Updated on

Flutter & Python Web-Socket Ft. Socket-IO (Part 3)

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
Enter fullscreen mode Exit fullscreen mode

socket_io_client:package is used for connecting Flutter application to python server using sockets.

shared_preferences:This is used for storing roomId and username locally for persistent authentication.

  • We are going to follow the following file structure:

output1

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

Imports.dart

Raw File

why do we Exports dart files into one and how we do it?

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

Raw File

  • 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

Raw File

  • Now replace following lines of codes in main.dart

main.dart

Raw File

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()));


Enter fullscreen mode Exit fullscreen mode
  • 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

login2

login3

Raw File

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!)));
                },
Enter fullscreen mode Exit fullscreen mode

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

chat2

chat3

Raw File

  • 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,
        },
        );

      });
Enter fullscreen mode Exit fullscreen mode

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

We are using stream-builder 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
                            });
Enter fullscreen mode Exit fullscreen mode
  • and same we are leaving the room using 'left' event.
 socket.emit('left',{
                        'username':widget.username,
                        'room':widget.roomId,
                      });

Enter fullscreen mode Exit fullscreen mode

and in the last we are clearing preferences.

Finally Outputs

output2
output3
output4

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....

Follow me:

Oldest comments (0)