Flutter - Other

Prevent Video Recording & Screenshot

Flutter

  1. Add flutter_windowmanager to pubspec.yaml.
  2. Add the code below. If needed to apply on complete app, then call it in main.dart file.
Future<void> secureScreen() async {
  await FlutterWindowManager.addFlags(FlutterWindowManager.FLAG_SECURE);
}

@override
void initState() {
  secureScreen();
  super.initState();
}


Android

  1. Locate MainActivity file and import Android.view.windowmanager.layoutparams.
  2. Add the code below.
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.oCreate(savedInstanceState);

  getWindow().addFlags(LayoutParams.FLAG_SECURE);
}


ios

  1. Locate Appdelegate.m file and add the code below.
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)LaunchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];
  //Override point for customization after application launch.
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    self.window.hidden = YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    self.window.hidden = NO;
}

@end

Randomly select an item from a list using Random from dart:math

import 'dart:math';

...

int min = 0;
int max = somList.length - 1;
Random rnd = new Random();

int r = min + rnd.nextInt(max - min);

return someList[r];

Reduced App Size

Enable Split-Per-ABI

flutter build apk --split-per-abi


In build.gradle:

splits {
  abi {
    enable true
    reset()
    include 'armeabi-v7a', 'arm64-v8a'
    universalApk false
  }
}


Enable Code + Resource Shrinking

In your build.gradle (same file as above):

gradle
buildTypes {
    release {
        shrinkResources true
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}


Then I created a simple proguard-rules.pro file in the android/app/ directory. This file prevents critical Flutter classes from being stripped out:

proguard
# Flutter wrapper classes
-keep class io.flutter.** { *; }
-keep class io.flutter.plugins.** { *; }
# Keep your plugin classes (adjust as needed)
-keep class com.yourapp.** { *; }
# Prevent shrinking of entry points
-keep class MainActivity
-keep class *.MainActivity { *; }

Remove '#' from URL

void main() {
  setUrlStrategy(PathUrlStrategy());
  runApp(MyApp());
}

Remove Duplicate Elements from List

var ids = [1, 4, 4, 4, 5, 6, 6];

//toSet and then toList
var distinctIds = ids.toSet().toList();

//Spread operators
var distinctIds = [...{...ids}];

RenderBox was not laid out

The RenderBox was not laid out error is often caused by one of two other errors :


  • Vertical viewport was given unbounded height
  • An InputDecorator...cannot have an unbounded width

Separate color class

Try to have all the colors in a single class for your application. Use a color class to set colors in flutter app. It will be easy to change the color everywhere at once.


Don't

style: Textstyle(color: Colors.white, fontsize: 14),


Do

class AppColors{
  static const Color red = Color(0xXFFFFO000);
  static const Color green = Color(oxFF4CAF50);
  static const Color errorRed Color(OxFFFF6E6E);
}
  
style: Textstyle(color: errorRed, fontsize: 14),

setState called during build

One way to avoid this error is to use the Navigator API to trigger the dialog as a route.


body: Center(
  child: ElevatedBut ton(
    child: Text ('Launch screen')
    onPressed: () {
      // Navigate to the second screen using a named route.
      Navigator.pushNamed (context, '/second');
      // Immediately show a dialog upon loading the second screen.
      Navigator.push(
        context,
        PageRouteBuilder (
          barrierDismissible : true,
          opaque: false,
          pageBuilder: (_, anim1, anim2) => MyDialog(),
        ),
      );
    }
  )
)

Setting SDK Version in Flutter by Modifying flutter.gradle

  1. Navigate to the flutter/packages/flutter_tools/gradle/.
  2. Use a text editor to open the flutter.gradle file located in the gradle folder.
  3. Inside the file, find and modify the compileSdkVersion, targetSdkVersion, and minSdkVersion to the desired API levels.
  4. After saving, run the following commands in your terminal to rebuild the Flutter app.


API levels

compileSdkVersion = 33
targetSdkVersion = 33
minSdkVersion = 21


commands

flutter clean
flutter pub get
flutter build <platform>  # e.g., flutter build apk

Shuffle List

var list = ['a', 'b', 'c', 'd'];

list.shuffle();

Specify types for class member

Always specify the type of member when its value type is known. Avoid using var when possible.


Do

int item = 10;
final Car bar = Car();
String name = 'john';
const int timeOut = 20;


Don't

var item = 10;
final car = Car();
const timeOut = 2000;

Spread Operator for Multiple Widgets (...)

For dynamically adding multiple widgets into a column or row, the spread operator (...) simplifies your code. It allows Flutter to automatically handle lists of widgets in a more efficient way.

Column(
  children: [
    ...myListOfWidgets,
  ],
);