That is How we can lock screen orientation in Flutter

compodoc

In the most of the appliations you have to lock the orientation of mobile app most of the time in only portrait mode. We do it in android and ios native applications and same we want to achieve when we are working on Flutter Apps.

How to do that?

We need to implement this in the main.dart file. First see the code then I will explain it in details

First you need to import services.dart from flutter package to achieve this.

import 'package:flutter/services.dart';

see the full code here.

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:kisan/my_home_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

final ThemeData kIOSTheme = new ThemeData(
  primarySwatch: Colors.orange,
  primaryColor: Colors.grey[100],
  primaryColorBrightness: Brightness.light,
);

final ThemeData kDefaultTheme = new ThemeData(
  primarySwatch: Colors.purple,
  primaryColor: Colors.black,
  accentColor: Colors.black,
  brightness: Brightness.light,
);



void main() {
  initFirestoreSettings();
  SystemChrome.setSystemUIOverlayStyle(
    SystemUiOverlayStyle(
      statusBarColor: Colors.white, //top bar color
      statusBarIconBrightness: Brightness.dark, //top bar icons
      systemNavigationBarColor: Colors.white, //bottom bar color
      systemNavigationBarIconBrightness: Brightness.dark, //bottom bar icons
    )
  );
  SystemChrome.setPreferredOrientations(
          [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown])
      .then((_) => runApp(new MyApp()));
}

void initFirestoreSettings() async {
  Firestore firestore = Firestore();
  await firestore.settings(timestampsInSnapshotsEnabled: true);
}



class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Kisan',
      debugShowCheckedModeBanner: false,
       theme: defaultTargetPlatform == TargetPlatform.iOS
          ? kIOSTheme
          : kDefaultTheme,
      home: MyHomePage(title: 'Welcome Kisan'),
    );
  }
}

One this you have to do here is that you have to do is wrap your MyApp Widget(App root widget) like this in main() function.

SystemChrome.setPreferredOrientations(
          [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown])
      .then((_) => runApp(new MyApp()));

Here we are only allowing portrait modes of screen only.

Hope you have enjoyed the topic I will come up with these kind of small handy scripts to make development easy for you. Thanks.


Tagged with:
CodeNextGen
Written by Sanjeev Kumar

Get notifications about new posts on Twitter, RSS or Email.