Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Preferred Orientation when Navigating back to home page

Tags:

flutter

dart

How to fix screen orientation cannot back to normal when press the back button?

here soruce code: https://github.com/iyansr/traffic-manager-master

I've set Orientation inside and outside void initState() on both page, but when i go back to homepage, the screen orientation still lanscape.

I want the homepage always in potrait mode and the second page is always landscape

on home.dart:

...
  @override
  void initState() {
    super.initState();
    // Set portrait orientation
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitDown,
      DeviceOrientation.portraitUp,
    ]);

    _dateTime = DateTime.parse(initDate);
  }
...

on counterpage.dart (landscape):

class _CounterPageState extends State<CounterPage> {
  @override
  void initState() {
    super.initState();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
  }
...

like image 381
Iyan Saputra Avatar asked Oct 14 '25 18:10

Iyan Saputra


1 Answers

initState() isn't called when you back, because your old page is still created, but not active. Maybe the simplest result here will be called setPrefferedOrintations() in dispose() method on second screen

class _CounterPageState extends State<CounterPage> {
  @override
  void initState() {
    super.initState();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
  }

  @override
  void dispose() {
    // Set portrait orientation
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitDown,
      DeviceOrientation.portraitUp,
    ]);
    super.dispose();
  }
}
like image 50
Mateusz Avatar answered Oct 17 '25 07:10

Mateusz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!