This is weird but below code is not working for me. I get a back arrow on the home screen when using below code.
First line below is for dismissing the dialog box. second one is to go to home screen.
Navigator.of(context, rootNavigator: true).pop();
Navigator.of(context).pushReplacementNamed(HomeScreen.id);
This is first time I am facing this kind of situation with pushReplacementNamed. what's going on here ?
It is probably because you have another screen in the stack. When you call pushReplacementNamed, it doesn't replace whole stack with the one you give. Can you try the following code;
// true don't work based on above query condition
Navigator.of(context).pushNamedAndRemoveUntil(HomeScreen.id, (Route<dynamic> route) => true);
// false works
Navigator.of(context).pushNamedAndRemoveUntil(HomeScreen.id, (Route<dynamic> route) => false);
That won't give the required result as you have already even popped the context away before calling another Navigator class. I tried the function Navigator.of(context).pushNamedAndRemoveUntil() but still got my HomeScreen pushed on stack twice with the back button on screen 1. Hence, I finally got this with the inbuilt function Navigator.of(context).popUntil(). You can run this dartpad code https://dartpad.dev/a10ed43452736b5c6b3d1abe6a7eda45 to view the desired effect or view the code below. Below is part of the code from the gist:
...
class ThirdPage extends StatelessWidget{
static const routeName = '/third';
#override
Widget build(BuildContext context){
void _nextPage(){
//Logic here - ***************************
Navigator.of(context).popUntil((Route<dynamic> route) => route.isFirst);
}
return Scaffold(
appBar: AppBar(
title: Text('Third Page'),
),
body: Center(
child: Text('Third Page'),
),
floatingActionButton: FloatingActionButton(
onPressed: _nextPage,
child: Icon(Icons.add),
),
);
}
}
Happy coding D:)
Related
I am creating an alarm clock application, and I want to show a full screen page to allow the user to dismiss the alarm when it triggers. Thats all working well but the issue arises when I want to close that page.
What I have tried
Currently, when the alarm triggers, I am pushing that page onto the navigation stack to make it visible:
App.navigatorKey.currentState?.pushNamedAndRemoveUntil(
alarmNotificationRoute,
(route) {
return (route.settings.name != '/alarm-notification') ||
route.isFirst;
},
);
And then pop it when user presses "Dismiss":
if (App.navigatorKey.currentState?.canPop() ?? false) {
App.navigatorKey.currentState?.pop();
}
My App routing code:
class App extends StatefulWidget {
const App({super.key});
static final GlobalKey<NavigatorState> navigatorKey =
GlobalKey<NavigatorState>();
#override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
#override
Widget build(BuildContext context) {
return MaterialApp(
...
navigatorKey: App.navigatorKey,
initialRoute: '/',
onGenerateRoute: (settings) {
switch (settings.name) {
case '/':
return MaterialPageRoute(builder: (context) => const RootScreen());
case '/alarm-notification':
return MaterialPageRoute(
builder: (context) {
return AlarmNotificationScreen();
},
);
default:
assert(false, 'Page ${settings.name} not found');
return null;
}
},
);
}
}
Current behavior
Now when I pop, it returns to the default route of the flutter app '/', even when the alarm triggered while the app was closed.
Expected behavior
The behavior I want is as follows:
If the app was in the foreground when alarm triggered, pressing dismiss should go back to the last screen (this is already working as expected)
If the app was in the background or closed when alarm triggered, pressing dismiss should send the app to background
If android decides to show a Heads Up Notification instead of a full page intent. pressing dismiss should do nothing
Thoughts
I am thinking that the cleanest way to do so would be to launch a standalone page/activity, which we can just close when we press dismiss. Is there anyway to do such a thing? I am fine with it being an android-only solution.
There appears to be a minimize_app package that does the "close to background" behavior you want. From there it's simply a matter of tracking where the page was navigated from and using conditional logic.
A possible implementation:
import 'package:minimize_app/minimize_app.dart';
...
// Set this variable when the app is opened via the alarm trigger
if (appWasInBackground) {
MinimizeApp().minimizeApp();
} else if (App.navigatorKey.currentState?.canPop() ?? false) {
App.navigatorKey.currentState?.pop();
}
I am using Flutter_bloc package to make a phone auth in flutte, everything work good, but my question is about adding events to the bloc, for example in my application, when i click on button like this code below, the event added to my loginBloc, and everything works good, but when i press back button in android device, and then return back by using normal navigater.pushNamed, and click the button again nothing happen? that mean the event not added to bloc or something like this? can anybody explain this problem? thanks in advance: this is my sample code to add event when click button:
child: RaisedButton(
onPressed: () {
if (_formKey.currentState.validate()) {
loginBloc.add(LoginPressesEvent(
phoNo: _phoneTextController.value.text));
}
},
For adding an 'Event' to 'Bloc' use this code:
BlocProvider.of<'YourBlocClass'>('blocContext').add('YourEvent()'));
'blocContext' is context parameter of `listener in BlocListener' :
BlocProvider(
create: (context) => BlocClass()..add(Fetch()),
child: BlocListener<BlocClass, BaseState>(
listener: (listenerContext, state) {
// listenerContext: store this parameter to Field
// and use that everywhere in your StateClass
},
or context parameter of 'builder in Bloc Builder`
BlocProvider(
create: (context) => BlocClass()..add(Fetch()),
child: BlocBuilder<IndexBloc, BaseState>(
builder: (builderContext, state) {
// builderContext: store this parameter to Field
// and use that everywhere in your StateClass
},
I am trying to achieve a very basic thing: Display Admob Banner ad on top. This works, but the Banner Ad slips inside the status bar and I couldn't find any way to make it display properly. Here is the sample code I am trying:
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomeView(),
);
}
}
class HomeView extends StatefulWidget {
#override
_HomeViewState createState() => _HomeViewState();
}
Future<void> _initAdMob() {
return FirebaseAdMob.instance.initialize(appId: AdManager.appId);
}
class _HomeViewState extends State<HomeView> {
// COMPLETE: Add _bannerAd
BannerAd _bannerAd;
// COMPLETE: Implement _loadBannerAd()
void _loadBannerAd() {
_bannerAd
..load()
..show(anchorType: AnchorType.top);
}
#override
void initState() {
_bannerAd = BannerAd(
adUnitId: AdManager.bannerAdUnitId,
size: AdSize.banner,
);
super.initState();
}
#override
Widget build(BuildContext context) {
return FutureBuilder<void>(
future: _initAdMob(),
builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
_loadBannerAd();
return SafeArea(
child: new Column(children: <Widget>[
Text('Sample text')
],),
);
},
);
}
}
This code produces the below output:
which obviously is wrong. The text is right at the place where it should be, however, the Banner ad is slipped inside the status bar, which is not what I intend. Also, since Google doesn't support providing positional arguments for the banner ad, I am completely helpless.
However, the Banner ad in the Google Codelab for Flutter works very well which is way beyond my understanding as a Flutter novice.
Can someone please shed a light and guide me on what's wrong with the sample code?
I used Navigator.push up to 6 screens to get to the payment page. After Payment, I want to push to the "Payment Successful" page then remove all the previous screens i.e using the back button will return to the very first screen.
NOTE: I have tried pushReplacementNamed and it doesn't work.
I figured it out. It was the Navigator.pushAndRemoveUntil function. Where i had to pass the PaymentSuccessful widget as the newRoute, and the "/Home" route as the predicate
_navPaymentSuccessful(){
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => PaymentSuccessful()
),
ModalRoute.withName("/Home")
);
}
Accepted Answer is correct. But you can try this too.
Navigator.pushAndRemoveUntil<dynamic>(
context,
MaterialPageRoute<dynamic>(
builder: (BuildContext context) => YourPageNameGoesHere(),
),
(route) => false,//if you want to disable back feature set to false
);
even simpler and I think a better way would be to do it this way,
this Schedules a callback for the end of the current persistent frame,to push to route /loginPage and removes all the previous routes,this way you can make sure that all the frames are rendered and then you navigate to next page.
SchedulerBinding.instance.addPostFrameCallback((_) {
Navigator.of(context).pushNamedAndRemoveUntil(
'/loginPage', (Route<dynamic> route) => false);
});
I would Suggest use WillPopScope in your Payment successful page and onWillPop method write following snippet of code:
return WillPopScope(
onWillPop: (){
Navigator.of(context)
.pushNamedAndRemoveUntil('/Home', (Route<dynamic> route) => false);
},
child: Scaffold()
};
Try this if you want pass arguments to new page:
Navigator.of(context).pushNamedAndRemoveUntil(
'/new-route-name',
arguments: {
any object
},
ModalRoute.withName("/the-route-name-that-you-want-back-to-it")
);
I'm new to Dart/Flutter and currently using the Flutter Camera Plugin but I am running into a problem with the CameraPreview for when the phone turns to landscape mode. The images stay vertical and don't rotate the 90degrees with the phone.
I have tried countless things including Transform.rotate(), but I can't seem to get the image to both, fill the screen and rotate 90degrees.
The pictures that were taken while the phone was sideways still saved in the correct orientation when I view them, but using the _cameraPreviewWidget.
Normal
Landscape
Adding SystemChrome.setPreferredOrientations() to my initState() & dispose() functions solved this problem for me.
import 'package:flutter/services.dart';
...
#override
void initState() {
super.initState();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
}
#override
void dispose() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
}
A package call camera_camera https://pub.dev/packages/camera_camera
has do great work and provide great feature you can reference his source code or fork directly.
about rotate issue, please use this package https://pub.dev/packages/native_device_orientation
and wrap body like this
return Scaffold(
body: NativeDeviceOrientationReader(builder: (context) {
NativeDeviceOrientation orientation =
NativeDeviceOrientationReader.orientation(context);
you can reference full code at
https://github.com/marslord/camera/blob/master/lib/cam.dart ,this is not camera_camera package and author use RotateBox
return RotatedBox(
quarterTurns: turns,
child: Transform.scale(
scale: 1 / controller.value.aspectRatio,
child: Center(
child: AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: CameraPreview(controller),
),
),
),
);
camera_camera package use this at line 76
return NativeDeviceOrientationReader(
useSensor: true,
builder: (context) {
NativeDeviceOrientation orientation =
NativeDeviceOrientationReader.orientation(context);
about fit screen issue
camera_camera package do this with below code full code is here https://github.com/gabuldev/camera_camera/blob/master/lib/page/camera.dart
return widget.mode ==
CameraMode.fullscreen
? OverflowBox(
maxHeight: size.height,
maxWidth: size.height *
previewRatio,
child: CameraPreview(
bloc.controllCamera),
)
: AspectRatio(
aspectRatio: bloc
.controllCamera
.value
.aspectRatio,
child: CameraPreview(
bloc.controllCamera),
);
execute result of camera_camera package can found on his github
execute result of https://github.com/marslord/camera
both check with real device and works
official camera plugin example rotate image can work with combine Native_device_orientation
and RotateBox , you can reference https://github.com/marslord/camera/blob/master/lib/cam.dart
but official camera plugin example fit screen issue will need to modify layout code
I would suggest use camera_camera's method, Stack CameraPreview and Button. it looks more like Native Camera App and easy to maintain landscape mode
official camera plugin example rotate image code snippet with combine Native_device_orientation and RotateBox
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: const Text('Camera example'),
),
body: NativeDeviceOrientationReader(builder: (context) {
NativeDeviceOrientation orientation =
NativeDeviceOrientationReader.orientation(context);
int turns;
switch (orientation) {
case NativeDeviceOrientation.landscapeLeft:
turns = -1;
break;
case NativeDeviceOrientation.landscapeRight:
turns = 1;
break;
case NativeDeviceOrientation.portraitDown:
turns = 2;
break;
default:
turns = 0;
break;
}
return Column(
children: <Widget>[
Expanded(
child: RotatedBox(
quarterTurns: turns,
child: Transform.scale(
scale: 1 / controller.value.aspectRatio,
child: Container(
child: Padding(
padding: const EdgeInsets.all(1.0),
child: AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: Center(
child: _cameraPreviewWidget(),
),
),
),
When you rotate your phone while using a camera the preview will stay vertical, however when you view the image it will be in landscape, try with the default camera app and it would be the same
You can obviously rotate your UI that is on top of the camera preview when the phone rotates
My solution;
using with this libraries; https://pub.dev/packages/image and https://pub.dev/packages/native_device_orientation
Future<void> takeAPicture()async{
pictureShooting=true;
final XFile image=await cameraController!.takePicture();
img.Image? _capturedImage=img.decodeImage(await image.readAsBytes());
final NativeDeviceOrientation currentOrientation=await _nativeDeviceOrientationCommunicator.orientation(useSensor: true);
switch(currentOrientation){
case NativeDeviceOrientation.landscapeRight: _capturedImage=img.copyRotate(_capturedImage!, 90);break;
case NativeDeviceOrientation.landscapeLeft: _capturedImage=img.copyRotate(_capturedImage!, 270);break;
case NativeDeviceOrientation.portraitDown: _capturedImage=img.copyRotate(_capturedImage!, 180);break;
default:
}
takenImage=Uint8List.fromList(img.encodePng(_capturedImage!));
pictureShooting=false;
showImageApprovalScreen=true;
}
In my case, a real Android device in Landscape orientation would show the appropriate camera preview content, but because the device wasn't "allowed" to rotate (due to app manifest/plist settings), it was showing as a strip where the Left to Right wide pixels were showing in a rectangle on the left side going from Bottom to Top, where that rectangle was small in order to fit in that dimension... so most of the screen was white empty space. On emulators, this phenomenon didn't occur (rotation worked as desired). The solution, after much searching and troubleshooting was to put some code in to modify what orientations were allowed, only while the camera preview was being displayed:
//allows any rotation (while camera preview is open)
Future<void> _enableRotation() async {
await SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
}
// may block rotation; sets orientation back to OS defaults for the app
Future<void> _backToOriginalRotation() async {
await SystemChrome.setPreferredOrientations([]);
}
I used await _enableRotation(); in initializing an ancestor of CameraPreview and I used await _backToOriginalRotation(); in disposing.
I used WillPopScope's onWillPop callback and await Navigator.of(context).maybePop<String>>(filepath); to close the view when a picture had been captured (and after the image had been saved to temp directory at the path filepath), so that the Android back button would also run the dispose and rotation code via onWillPop.
EDIT: After testing on both iOS and Android actual devices, this fix worked on Android phones, but did not work on iPhones. iPhones still displayed the camera preview in a small rotated strip when the device is landscape. This is using camera package version 0.8.1+7.
EDIT2: After updating the iOS info.plist to allow any device orientation, this approach worked for iPhones too. However, there are still devices and situations where the preview orientation (and thus captured image orientation) are incorrect, leading to about 50% of captured landscape photos being saved sideways (in portrait orientation). Reproduction of the problem seems possible if you start your device in landscape orientation when you open the camera preview and don't rotate your device before capturing (or if device auto-rotate screen setting is off).
class _VideoPlayerWidgetState extends State<VideoPlayerWidget> {
VideoPlayerController _videoPlayerController;
ChewieController _chewieController;
#override
void initState() {
super.initState();
initializePlayer();
}
Future<void> initializePlayer() async {
// widget.url put url video file path
_videoPlayerController =
_videoPlayerController = VideoPlayerController.network(widget.url);
await Future.wait([_videoPlayerController.initialize()]);
_chewieController = ChewieController(
videoPlayerController: _videoPlayerController,
autoPlay: true,
looping: true,
);
}
bool useSensor = true;
bool portrait;
#override
Widget build(BuildContext context) {
return NativeDeviceOrientationReader(
builder: (context) {
NativeDeviceOrientation orientation =
NativeDeviceOrientationReader.orientation(context);
portrait = orientation == NativeDeviceOrientation.portraitUp;
if(orientation == NativeDeviceOrientation.landscapeLeft){
SystemChrome.setPreferredOrientations([
!portrait
? DeviceOrientation.landscapeLeft
: DeviceOrientation.portraitUp,
!portrait
? DeviceOrientation.landscapeLeft
: DeviceOrientation.portraitDown,
]);
}else{
SystemChrome.setPreferredOrientations([
!portrait
? DeviceOrientation.landscapeRight
: DeviceOrientation.portraitUp,
!portrait
? DeviceOrientation.landscapeRight
: DeviceOrientation.portraitDown,
]);
}
return _chewieController != null &&
_chewieController.videoPlayerController.value.isInitialized
? Chewie(
controller: _chewieController,
)
: Center(child: CircularProgressIndicator());
},
useSensor: useSensor,
);
}
#override
void dispose() {
_videoPlayerController.dispose();
_chewieController.dispose();
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
super.dispose();
}
}