How to change screen orientation in flutter?

This Article is posted by seven.srikanth at 11/14/2022 4:50:19 PM



You can do this by adding the following code to your main function.

WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft]);
Now import the services.dart package using the below code.

import 'package:flutter/services.dart';
This should do the trick.
You can try landscaperight, portraitDown or portraitUp.
Here is the complete code for the example.

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main(List<String> args) {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft]);
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @ override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: MyContainer(),
      ),
    );
  }
}
class MyContainer extends StatelessWidget {
  const MyContainer({
    super.key,
  });
  @ override
  Widget build(BuildContext context) {
    var screenOrientation = MediaQuery.of(context).orientation;
    return Center(
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 100),
        child: Padding(
          padding: const EdgeInsets.all(28.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const SizedBox(
                height: 20,
              ),
              Text(
                'Screen Orientation - $screenOrientation ',
                style: const TextStyle(fontSize: 18.0),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
Thanks,
Srikanth

Tags: screen orientation in flutter








0 Comments
Login to comment.
Recent Comments

Be the first to Comment. You can ask a Query or Share your toughts or Just say thanks.


© 2018 - Fluttercentral | Email to me - seven.srikanth@gmail.com