Show running clock on flutter - android

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}";
});
}
}

Related

Splashscreen flutter, prevent back button

I've made a custom Splashscreen but when I press back button from statless widget, it will go back to Splashcreen "Stateful widget". I've tried WillPopBack but it not work or at least I was not able to use it. How to prevent statless widget to go back to stateful widget?
Here my code:
void main() {
runApp(const 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(
title: 'Flutter Demo',
theme: ThemeData(primarySwatch: Colors.blue, fontFamily: 'Monserrat'),
home: const 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();
}
class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
#override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 4), () {
Navigator.of(context).push(
PageRouteBuilder(
transitionDuration: Duration(milliseconds: 1000),
pageBuilder: (BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation) {
return MainScreen();
},
transitionsBuilder: (BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child) {
return Align(
child: FadeTransition(
opacity: animation,
child: child,
),
);
},
),
);
});
}
#override
Widget build(BuildContext context) {
return [...]
}
}
class MainScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return [...]
}
}
Thanks in advance
Use pushReplacement instead of push like
super.initState();
Future.delayed(Duration(seconds: 4), () {
Navigator.of(context).pushReplacement( //< this
PageRouteBuilder(
transitionDuration: Duration(milliseconds: 1000),
pageBuilder: (BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation) {
return MainScreen();
},
More about push and pushReplacement

showing black screen on backpress Flutter

I am using Webview with WillPopScope, webview internal back button is working fine but on the first page back press is not working.
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SafeArea(child: MyHomePage()),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
InAppWebViewController _controller;
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () => canGoBack(context),
child: Scaffold(
body: InAppWebView(
initialUrlRequest:
URLRequest(url: Uri.parse("https://www.google.com/")),
onWebViewCreated: onWebviewCreated,
),
),
);
}
void onWebviewCreated(InAppWebViewController controller) {
_controller = controller;
}
canGoBack(BuildContext context) async {
if (await _controller.canGoBack()) {
_controller.goBack();
return Future.value(false);
} else {
return Future.value(true);
}
}
}
tried with
canGoBack(BuildContext context) async {
if (await _controller.canGoBack()) {
_controller.goBack();
return Future.value(false);
} else {
Navigator.pop(context, true);
return Future.value(false);
}
}
the issue is showing the black if there is no webview history.
You don't have any previous root and you're using
Navigator.pop(context, true); // in canGoBack function
That's cause to issue. Remove that line and it will work.

How to mention the Channel and Event name in flutter websockets

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?

Flutter build apk release crashing when opening the app only in first time

Apparently the error is actually in the main.dart -- crashing when opening the app only in first time
I am developing a flutter application with a welcome screen that appears only the first time the app is opened, after that the main screen is a webview
This is my main.dart
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
color: Colors.amber,
home: new Splash(),
);
}
}
class Splash extends StatefulWidget {
#override
SplashState createState() => new SplashState();
}
class SplashState extends State<Splash> with AfterLayoutMixin<Splash> {
Future checkFirstSeen() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool _seen = (prefs.getBool('seen') ?? false);
if (_seen) {
Navigator.of(context).pushReplacement(
new MaterialPageRoute(builder: (context) => new Home()));
} else {
await prefs.setBool('seen', true);
Navigator.of(context).pushReplacement(
new MaterialPageRoute(builder: (context) => new IntroScreen()));
}
}
#override
void afterFirstLayout(BuildContext context) => checkFirstSeen();
#override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new Text('Carregando...'),
),
);
}
}
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Entrega na Obra',
home: HomePage(),
);
}
}
class IntroScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Entrega na Obra',
home: WelcomeScreen(),
);
}
}

I am trying to create a splash screen in my project but this code is not working. it just shows the splash screen forever

I am trying to create a splash screen in my project but this code is not working. it just shows the splash screen forever. it doesn't switch to the home screen. Any help? (I want to create an app that starts with a splash screen but i don't want this splash screen to be a photo)
import 'dart:async';
void main() {
runApp( splash(),);
}
// ignore: camel_case_types
class splash extends StatefulWidget {
#override
_splashState createState() => _splashState();
}
// ignore: camel_case_types
class _splashState extends State<splash> {
#override
void initState() {
super.initState();
Timer(
Duration(seconds: 5),
() => Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (BuildContext context) => home(),),),);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(child: Text("Splash Screen"),)
),
);
}
}
class home extends StatefulWidget {
#override
_homeState createState() => _homeState();
}
// ignore: camel_case_types
class _homeState extends State<home> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("Home"),
),
),
);
}
}```
Separate your MaterialApp from your splash
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp(),);
}
class Splash extends StatefulWidget {
#override
_SplashState createState() => _SplashState();
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Splash(),
);
}
}
class _SplashState extends State<Splash> {
#override
void initState() {
super.initState();
Timer(
Duration(seconds: 5),
() => Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (BuildContext context) => Home(),),),);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Text("Splash Screen"),)
);
}
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("Home"),
),
),
);
}
}

Categories

Resources