Skip to content

Instantly share code, notes, and snippets.

@ctkqiang
Last active May 14, 2020 03:27
Show Gist options
  • Save ctkqiang/1bb65b61d115c2cdd1014a5a50306e40 to your computer and use it in GitHub Desktop.
Save ctkqiang/1bb65b61d115c2cdd1014a5a50306e40 to your computer and use it in GitHub Desktop.
===============
//main.dart
import 'package:flutter/material.dart';
import './chat.dart';
void main() {
runApp(ChatApp());
}
class ChatApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: chat(),
);
}
}
=============
// chat.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_socket_io/flutter_socket_io.dart';
import 'package:flutter_socket_io/socket_io_manager.dart';
class chat extends StatefulWidget {
@override
State<StatefulWidget> createState() {
_chatState createState(){
_chatState();
}
}
}
class _chatState extends State<chat> {
static SocketIO _socketIO;
static List<String> _messages;
static double _height, _width;
static TextEditingController _textController;
static ScrollController _scrollController;
@override
void initState() {
// Start the message list :
_messages = List<String>();
// Initializing the TextEditingController and ScrollController:
_textController = TextEditingController();
_scrollController = ScrollController();
// Magic out the socket
_socketIO = SocketIOManager().createSocketIO("https://monjochattest.herokuapp.com", "/");
// Call init before doing anything with the socket
_socketIO.init();
// listen to an event: {must be must with "index.js"}
_socketIO.subscribe('receive_message', (jsonData) {
// Convert the Json data into native Map:
Map<String, dynamic> data = json.decode(jsonData);
// honestly I hate widgets: :(
this.setState(() => _messages.add(data["message"]));
_scrollController.animateTo(_scrollController.position.maxScrollExtent,
duration: Duration(milliseconds: 600), curve: Curves.ease);
});
// Now Finally connect to the socket
_socketIO.connect();
super.initState();
}
Widget _buildSingleMessage(int _index) {
return Container(
alignment: Alignment.centerLeft,
child: Container(
padding: const EdgeInsets.all(20.0),
margin: const EdgeInsets.only(bottom: 20.0, left: 20.0),
decoration: BoxDecoration(
color: Colors.deepPurple,
borderRadius: BorderRadius.circular(20.0),
),
child: Text(
_messages[_index],
style: TextStyle(color: Colors.white, fontSize: 15.0),
),
),
);
}
Widget _buildMessageList() {
return Container(
height: _height * 0.8,
width: _width,
child: ListView.builder(
controller: _scrollController,
itemCount: _messages.length,
itemBuilder: (BuildContext context, int index) {
return _buildSingleMessage(index);
},
),
);
}
Widget _buildChatInput() {
return Container(
width: _width * 0.7,
padding: const EdgeInsets.all(2.0),
margin: const EdgeInsets.only(left: 40.0),
child: TextField(
decoration: InputDecoration.collapsed(
hintText: 'Send a message...',
),
controller: _textController,
),
);
}
Widget _buildSendButton() {
return FloatingActionButton(
backgroundColor: Colors.deepPurple,
onPressed: () {
//Check if the textfield has text or not
if (_textController.text.isNotEmpty) {
//Send the message as JSON data to send_message event
_socketIO.sendMessage(
'send_message', json.encode({'message': _textController.text}));
//Add the message to the list
this.setState(() => _messages.add(_textController.text));
_textController.text = '';
//Scrolldown the list to show the latest message
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: Duration(milliseconds: 600),
curve: Curves.ease,
);
}
},
child: Icon(
Icons.send,
size: 30,
),
);
}
Widget _buildInputArea() {
return Container(
height: _height * 0.1,
width: _width,
child: Row(
children: <Widget>[
_buildChatInput(),
_buildSendButton(),
],
),
);
}
@override
Widget build(BuildContext context) {
_height = MediaQuery.of(context).size.height;
_width = MediaQuery.of(context).size.width;
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: <Widget>[
SizedBox(height: _height * 0.1),
_buildMessageList(),
_buildInputArea(),
],
),
),
);
}
}
=== server side : nodejs
/**
* This is @Prototype
* This is A server Side using Nodejs
* @Written By John Melody
*/
const app = require("express") ()
const http = require("http").createServer(app);
const socketio = require("socket.io")(http)
/**
* @param
* @note I created a test server and using Heroku cli
* just to get the feeling how it work , where Can I encryption and
* push the $hashes to the server
* @url https://monjochattest.herokuapp.com/
* @global https://git.heroku.com/monjochattest.git
*/
app.get("/", (req, res) => {
res.send("Test");
});
socketio.on("connection", (userSocket) => {
userSocket.on("send_message", (data) => {
userSocket.broadcast.emit("receive_message", data);
});
});
// http.listen(8080);
// Deployment to heroku:
http.listen(process.env.PORT);
///////////////////error I got :
An Observatory debugger and profiler on SM G530H is available at: http://127.0.0.1:57654/wZm5c2IebL8=/
I/flutter ( 4069): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 4069): The following NoSuchMethodError was thrown building Builder:
I/flutter ( 4069): The method '_debugTypesAreRight' was called on null.
I/flutter ( 4069): Receiver: null
I/flutter ( 4069): Tried calling: _debugTypesAreRight(Instance of 'chat')
I/flutter ( 4069): The relevant error-causing widget was:
I/flutter ( 4069): MaterialApp
I/flutter ( 4069): file:///D:/Mynapse/MobileApplication/Documents/Design/Research/Encryption/encryption_test_app/lib/main.dart:11:12
I/flutter ( 4069): When the exception was thrown, this was the stack:
I/flutter ( 4069): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
I/flutter ( 4069): #1 new StatefulElement.<anonymous closure> (package:flutter/src/widgets/framework.dart:4594:19)
I/flutter ( 4069): #2 new StatefulElement (package:flutter/src/widgets/framework.dart:4605:6)
I/flutter ( 4069): #3 StatefulWidget.createElement (package:flutter/src/widgets/framework.dart:894:38)
I/flutter ( 4069): ... Normal element mounting (115 frames)
I/flutter ( 4069): #118 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
I/flutter ( 4069): #119 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5947:32)
I/flutter ( 4069): ... Normal element mounting (238 frames)
I/flutter ( 4069): #357 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
I/flutter ( 4069): #358 Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
I/flutter ( 4069): #359 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1148:16)
I/flutter ( 4069): #360 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1119:5)
I/flutter ( 4069): #361 RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:1061:17)
I/flutter ( 4069): #362 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2607:19)
I/flutter ( 4069): #363 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1060:13)
I/flutter ( 4069): #364 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:941:7)
I/flutter ( 4069): #365 WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:922:7)
I/flutter ( 4069): (elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment