Code
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://192.168.0.164:6001/app/KEY'),
),
);
}
}
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> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: StreamBuilder(
stream: widget.channel.stream,
builder: (context, snapshot) {
if(snapshot.hasError)
print(snapshot.error);
else {
widget.channel.sink.add("123");
print("XXX : ${snapshot.data}");
}
return Padding(
padding: const EdgeInsets.symmetric(vertical: 24.0),
child: Text(snapshot.hasData ? '${snapshot.data}' : ''),
);
},
),
),
);
}
#override
void dispose() {
widget.channel.sink.close();
super.dispose();
}
}
The output of the Print Statement is
XXX : {"event":"pusher:connection_established","data":"{"socket_id":"943971557.707744157","activity_timeout":30}"}
It does not fetch refreshed data as the Event and Channel isn't mentioned for my laravel backend. Is there a way that can be mentioned or have i got it wrong somewhere else?
Related
Lets say i have a button. So..
String buttonTitle = "Upload";
Above is the button title.
Now i have set this in my text of the button. When i upload something, i want this text to be Uploaded so i use setState method for that and hence the title of the button will be updated. But let's suppose i have 100s of buttons which just says Upload and later have to be changed to just Uploaded if something has been uploaded using that button, am i going to create 100 Strings here? This approach doesn't seem good enough to me. Is there a better approach for this in flutter ?
Check this widget as you expect . click on main button it will update all button state after 3 second like uploading
class MyHomePages2 extends StatefulWidget {
MyHomePages2({Key? key}) : super(key: key);
var Upload = "Upload";
#override
State<MyHomePages2> createState() => _MyHomePages2State();
}
class _MyHomePages2State extends State<MyHomePages2> {
#override
Widget build(BuildContext context) {
return ListView(
children: [
ElevatedButton(
onPressed: () {
setState(() {
widget.Upload = "upload";
});
Future.delayed(Duration(seconds: 3), () {
setState(() {
widget.Upload = "uploaded";
});
});
},
child: Text("MainUpload")),
...List.generate(
100,
(index) => Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () {}, child: Text("$index ${widget.Upload}")),
))
],
);
}
}
SampleCode Dartpad live code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
int myvalue = 0;
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
#override
void initState() {
// functions().then((int value) {
// setState(() {
// myvalue = value;
// });
// future is completed you can perform your task
// });
}
Future<int> functions() async {
// do something here
return Future.value();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: MyHomePages2(),
);
}
}
class MyHomePages2 extends StatefulWidget {
MyHomePages2({Key? key}) : super(key: key);
var Upload = "Upload";
#override
State<MyHomePages2> createState() => _MyHomePages2State();
}
class _MyHomePages2State extends State<MyHomePages2> {
#override
Widget build(BuildContext context) {
return ListView(
children: [
ElevatedButton(
onPressed: () {
setState(() {
widget.Upload = "upload";
});
Future.delayed(Duration(seconds: 3), () {
setState(() {
widget.Upload = "uploaded";
});
});
},
child: Text("MainUpload")),
...List.generate(
100,
(index) => Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () {}, child: Text("$index ${widget.Upload}")),
))
],
);
}
}
This type of dropdown.. I have tried more times in using a ListTile widget.
You have to use a RadioListTile for this purpose. this code is from the flutter documentation, you can try it:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatefulWidget(),
),
);
}
}
enum SingingCharacter { lafayette, jefferson }
/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
SingingCharacter? _character = SingingCharacter.lafayette;
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
RadioListTile<SingingCharacter>(
title: const Text('Lafayette'),
value: SingingCharacter.lafayette,
groupValue: _character,
onChanged: (SingingCharacter? value) {
setState(() {
_character = value;
});
},
),
RadioListTile<SingingCharacter>(
title: const Text('Thomas Jefferson'),
value: SingingCharacter.jefferson,
groupValue: _character,
onChanged: (SingingCharacter? value) {
setState(() {
_character = value;
});
},
),
],
);
}
}
Using this code brings me this warning when I run :
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xffebebeb),
body: AnimatedCrossFade(
firstChild: SplashScreen1(),
secondChild: SplashScreen2(),
crossFadeState:
!phaseTwo ? CrossFadeState.showFirst : CrossFadeState.showSecond,
duration: Duration(seconds: 1),
)
);
}
SplashScreen1()
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xffebebeb),
);
}
SplashScreen2()
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xffebebeb),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Image.asset('assets/images/splash_image_1.png'),
],
),
);
}
You can copy paste run full code below
You can replace Scaffold of SplashScreen1 and SplashScreen2 with Container
code snippet
class SplashScreen1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: const Color(0xffebebeb),
);
}
}
working demo
full code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool phaseTwo = false;
#override
void initState() {
super.initState();
Future.delayed(const Duration(seconds: 3), () {
setState(() {
phaseTwo = true;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xffebebeb),
body: AnimatedCrossFade(
firstChild: SplashScreen1(),
secondChild: SplashScreen2(),
crossFadeState:
!phaseTwo ? CrossFadeState.showFirst : CrossFadeState.showSecond,
duration: Duration(seconds: 1),
));
}
}
class SplashScreen1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: const Color(0xffebebeb),
);
}
}
class SplashScreen2 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: const Color(0xffebebeb),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Image.network('https://picsum.photos/250?image=9'),
],
),
);
}
}
I want to implement a call back from a Stateful widget to another Stateful Widget. (child to parent). The hierarchy is Task (contains) -> ItemBought -> addImage
How do i implement this? Also will the callback function be defined in the Stateful widget or in its state?
This is my current code:
Task.dart
import 'package:flutter/material.dart';
import 'package:flutter_convertor/ItemBought.dart';
class task extends StatelessWidget{
#override
...
}
class taskScreen extends StatefulWidget{
#override
taskState createState() => new taskState();
}
class taskState extends State<taskScreen> {
bool isButtonEnabled = false;
//Callback function i want to call in order to change the state of my Button
formReady(){
setState(() {
isButtonEnabled = !isButtonEnabled ;
});
}
#override
Widget build(BuildContext context) {
Column taskScreen = Column(
children: <Widget>[...
ItemBought(), //ITEMBOUGHT WIDGET
...
Column(
children: <Widget>[
FlatButton(
onPressed: isButtonEnabled ? _completePage : null,
child: Text(
...
),
),
],
)]);
return Scaffold(
appBar: AppBar(
title: Text('Task Screen')),
body: taskScreen,
);
} }
ItemBought.dart
import 'package:flutter/material.dart';
import 'package:flutter_convertor/addImage.dart';
class ItemBought extends StatefulWidget{
#override
_ItemBoughtState createState() => _ItemBoughtState();
}
class _ItemBoughtState extends State<ItemBought> {
...
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget> [
...
addImage(),
...
]
)
);
}
}
addImage.dart
import 'package:flutter/material.dart';
import 'package:flutter_convertor/task.dart';
class addImage extends StatefulWidget{
const addImage({this.formReady});
final VoidCallback formReady;
#override
_addImageState createState() => _addImageState();
}
class _addImageState extends State<addImage> {
// const void({taskState.formReady});
// final VoidCallback formReady;
#override
Widget build(BuildContext context) {
return Container(
child: TextField(
onChanged: (text){
formReady(); //ERROR: The method formReady is not defined for the class _addImageState
},
)
);
}
}
How do i call the function formReady from the widget addImage ?
EDIT:
I tried this code, and removed all compile errors however still not getting the desired result:
in addImage.dart
TextField(
onChanged: (text){
addImage().formReady;
}
)
in Itembought.dart
addImage(formReady: (){
ItemBought().formReady;
}
in task.dart
ItemBought(formReady: (){
this.formReady();
}),
class task extends StatelessWidget {
#override
....
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new ItemBought(callback: (data){
String receivedData = data;
},)
],
),
),
);
}
}
class ItemBought extends StatefulWidget {
final void Function(String data) callback;
const ItemBought({Key key, this.callback}) : super(key: key);
#override
_ItemBoughtState createState() => _ItemBoughtState();
}
class _ItemBoughtState extends State<ItemBought> {
#override
Widget build(BuildContext context) {
return Container(
child: new FlatButton(onPressed: (){
widget.callback("Item Id Or name");
}, child: new Text("Bought Item"),),
);
}
}
I wanted to know if there is any way to show a real time clock in dart?
Date and time (e.g 11/14/2018 19:34) and the time will continue to run.
Time can be taken from the device itself.
The below uses the intl plugin to format the time into MM/dd/yyyy hh:mm:ss. Make sure to update your pubspec.yaml.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Time Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Time Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _timeString;
#override
void initState() {
_timeString = _formatDateTime(DateTime.now());
Timer.periodic(Duration(seconds: 1), (Timer t) => _getTime());
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Text(_timeString),
),
);
}
void _getTime() {
final DateTime now = DateTime.now();
final String formattedDateTime = _formatDateTime(now);
setState(() {
_timeString = formattedDateTime;
});
}
String _formatDateTime(DateTime dateTime) {
return DateFormat('MM/dd/yyyy hh:mm:ss').format(dateTime);
}
}
Simplest solution:
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class ClockWidget extends StatelessWidget {
const ClockWidget({super.key});
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: Stream.periodic(const Duration(seconds: 1)),
builder: (context, snapshot) {
return Text(DateFormat('MM/dd/yyyy hh:mm:ss').format(DateTime.now()));
},
);
}
}
Put it anywhere you like.
This is the same code which Albert had given, but in case you don't want to use the intl package, you can make these changes to this code:
import 'package:flutter/material.dart';
import 'dart:async';
void main () => runApp(MyApp());
class MyApp extends StatelessWidget{
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primarySwatch: Colors.red),
home: FlutterTimeDemo(),
);
}
}
class FlutterTimeDemo extends StatefulWidget{
#override
_FlutterTimeDemoState createState()=> _FlutterTimeDemoState();
}
class _FlutterTimeDemoState extends State<FlutterTimeDemo>
{
String _timeString;
#override
void initState(){
_timeString = "${DateTime.now().hour} : ${DateTime.now().minute} :${DateTime.now().second}";
Timer.periodic(Duration(seconds:1), (Timer t)=>_getCurrentTime());
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Fluter Test'),),
body:Center(
child: Text(_timeString, style: TextStyle(fontSize: 30),),
),
);
}
void _getCurrentTime() {
setState(() {
_timeString = "${DateTime.now().hour} : ${DateTime.now().minute} :${DateTime.now().second}";
});
}
}