showing black screen on backpress Flutter - android

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.

Related

Missing concrete implementation of 'StatefulWidget.createState'

i am trying to achieve back page where in web veiw customer is moved out of the page instead going back which throws above error.StatefulWidget requires override method createState.All identations mark checked but still throwing error.where i am going wrong.
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createstate() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late WebViewController _webViewController;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
toolbarHeight:0,
), // AppBar
body: WillPopScope(
onWillPop: () async {
if(await _webViewController.canGoBack()){
_webViewController.goBack();
return false;
}
else {
return true;
}
} ,
child: WebView(
initialUrl: 'https://www.example.com',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController controller) {
_webViewController = controller;
},
), // WebView
), // WillPopScope
); // scaffold
}
}
In createState(), State's S should be Capital
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
void main() => runApp(const MaterialApp(home: HomePage()));
class HomePage extends StatefulWidget {
const HomePage({Key key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
WebViewController _webViewController;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
toolbarHeight:0,
), // AppBar
body: WillPopScope(
onWillPop: () async {
if(await _webViewController.canGoBack()){
_webViewController.goBack();
return false;
}
else {
return true;
}
} ,
child: WebView(
initialUrl: 'https://www.google.com',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController controller) {
_webViewController = controller;
},
), // WebView
), // WillPopScope
); // scaffold
}
}

how use the same as --disable-web-security on android emulator

I develop a flutter application in my laptop, and try to get data from rest api,
Ok, for showing data in chrome I add '--disable-web-security' this linkin spesific file and it work fine to show data from api to chrome emulator, but how can i show data in android emulator, because android emulator dont show data,
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
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',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var items = [];
#override
void initState() {
refreshUser();
super.initState();
}
Future refreshUser() async {
//Uri uri = Uri.parse('https://localhost:44305/api/CarModel');
final response = await http.get(uri, headers: {
'Content-type': 'application/json',
"Access-Control-Allow-Origin": "*", // Required for CORS support to work
"Access-Control-Allow-Credentials":
'true', // Required for cookies, authorization headers with HTTPS
"Access-Control-Allow-Headers":
"Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,locale",
"Access-Control-Allow-Methods": "POST, GET,OPTIONS"
});
var data = json.decode(response.body);
items = [];
setState(() {
for (var i = 0; i < data.length; i++) {
items.add(data[i]['name']);
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: RefreshIndicator(
onRefresh: refreshUser,
child: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
);
},
),
),
);
}
}

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

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

Show running clock on flutter

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

Categories

Resources