Flutter - Other

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. '),
  )
)        

Understanding the pubspec.yaml File

File Structure and Syntax


  • The pubspec.yaml file is written in YAML (YAML Ain't Markup Language), which is a human-readable data serialization standard.
  • YAML uses indentation to represent hierarchy, so it's important to maintain consistent spacing (two spaces are standard) and avoid tabs.


Key Sections of pubspec.yaml

Here's an overview of the primary sections you'll find in a pubspec.yaml file:


Metadata

At the top of the file, you'll find metadata about your project:

name: your_project_name
description: A brief description of your project
publish_to: 'none' # Remove this line if you want to publish to pub.dev
version: 1.0.0+1 # The version number and build number


  • name: The name of your package or project. It should be lowercase and can include underscores.
  • description: A short description of what your package does.
  • publish_to: Specifies where the package will be published. Use 'none' to prevent publishing to pub.dev.
  • version: Defines the version of your package. The format is major.minor.patch+build.


Environment

This section specifies the Dart SDK version your project supports:

environment:
  sdk: '>=2.12.0 <3.0.0'


  • sdk: Use a version constraint to define the minimum and maximum versions of the Dart SDK that your project is compatible with.


Dependencies

This section lists the packages your project depends on:

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  http: ^0.14.0


  • dev_dependencies: Use this to list packages that are only needed for development and testing.


Flutter Specific

If your project is a Flutter project, you'll want to include a flutter section:

flutter:
  uses-material-design: true
  assets:
    - assets/images/
    - assets/icons/


  • uses-material-design: Set this to true to enable Material Design features in your app.
  • assets: List assets (like images or fonts) that should be included in your app. You can specify individual files or entire directories.


Fonts

To include custom fonts in your project, use the following structure:

fonts:
  - family: Roboto
    fonts:
      - asset: fonts/Roboto-Regular.ttf
      - asset: fonts/Roboto-Bold.ttf
        weight: 700


  • fonts: Define custom fonts and their variations. You can specify different weights and styles.


Dependency Overrides

In some cases, you might need to override specific dependencies:

dependency_overrides:
  http: ^0.13.3


  • dependency_overrides: Use this to specify a version of a dependency that should be used instead of the version specified by other packages.


Best Practices


  • Keep it Clean: Remove any unnecessary comments or empty lines to maintain readability.
  • Version Control: Regularly update dependency versions and ensure compatibility.
  • Use Semantic Versioning: Follow semantic versioning to avoid conflicts and issues during dependency resolution.


Commands to Manage Dependencies

You can manage dependencies in your project using the following commands in the terminal:


  • Get Dependencies: This command fetches the packages listed in pubspec.yaml. flutter pub get
  • Upgrade Dependencies: This updates all dependencies to the latest compatible versions. flutter pub upgrade


Example of a Complete pubspec.yaml

Here's an example of a complete pubspec.yaml file for a Flutter project:

name: my_flutter_app
description: A sample Flutter application
publish_to: 'none'
version: 1.0.0+1

environment:
  sdk: '>=2.12.0 <3.0.0'

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  http: ^0.14.0

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true
  assets:
    - assets/images/
    - assets/icons/
  fonts:
    - family: Roboto
      fonts:
        - asset: fonts/Roboto-Regular.ttf
        - asset: fonts/Roboto-Bold.ttf
          weight: 700

dependency_overrides:
  http: ^0.13.3