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];

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,
  ],
);

Understanding Boxes

ConstrainedBox

- It constraints size of it's child, as per the given values.

- The size of ConstrainedBox itself depends on it's parent.

// Restrict the width between 70 — 150
ConstrainedBox(
  constraints: Boxconstraints(
    minWidth: 70, maxWidth: 150,
  ),
  child: AnyWidget(),
)     


UnconstrainedBox

- UnconstrainedBox imposes no constraints on its child.

- It renders the child as if it were alone on an infinite canvas with no constraints.

// No restriction applied on the child
UnconstrainedBox(
  child: AnyWidget(),
)


OverflowBox

- OverflowBox is similar to UnconstrainedBox the difference is that it won't display any warnings if the child doesn't fit the space.

- That is, it allows overflow.

// Will overflow the width after 150 px
OverflowBox (
  minWidth: 70,
  maxWidth: 150,
  child: AnyWidget(),
)


LimitedBox

- As the name suggests, it limits the size of its child.

- Difference between ConstrainedBox and LimitedBox is that, the later limits only when it gets infinite constraints,

// limits the width to 100 px
UnconstrainedBox(
  child: LimitedBox(
    maxWidth: 100,
    child: AnyWidget(),
  )
)        


FittedBox

- FittedBox will increase or decrease the size of it's child, until it is completely filled.

- In the example, FittedBox scales the Text until it fills all of the available width.

// Text size will increase to occupy all 100 px
Container(
  width: 100.0,
  child: FittedBox(
    child: Text('l am fit. '),
  )
)