This article shows you how to disable the landscape mode in Flutter.
The Steps
1. Import the services library to your main.dart file:
import 'package:flutter/services.dart';
Note that the services library comes along with Flutter and you DO NOT need to install any third-party plugin.
2. Add the code snippet below to the main() function in your main.dart file:
void main() {
// add these lines
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
// run app
runApp(MyApp());
}
3. Restart your app (not using hot reload) and check the results by rotating the Android and iOS simulators.
A Complete Example
Preview:
The full code:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Kindacode.com',
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Kindacode.com'),
),
body: const Center(
child: Text(
'Hello',
style: TextStyle(fontSize: 100),
),
),
);
}
}
If you want to display different content based on device orientation instead of disabling the landscape mode, read also this article: Flutter – Show different content based on device orientation.
If you would like to learn more about Flutter, take a look at the following articles:
- Flutter SliverList
- Flutter Transform examples – Making fancy effects
- Flutter: Scrolling to the desired item in a ListView
- Flutter Cupertino Button – Tutorial and Examples
You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.