Flutter - Other

How to Remove The Debug Banner in Flutter App ?

Flutter SDK Folder

  1. Go to ..\flutter\packages\flutter\lib\src\material.
  2. Open app.dart.
  3. Look for this.debugShowCheckedModeBanner and change the value from true to false.


Flutter Application

Add debugShowCheckedModeBanner: false to main.dart.

How to Run Tasks Without Freezing the UI

Example of Freezing the UI in Flutter

int complexTask() {
  int total = 0;
  for (int i = 0; i < 1000000000; i++) {
    total += i;
  }
  return total;
}

// Simple Flutter app setup with a button to trigger a heavy task
ElevatedButton(
  onPressed: () {
    int result = complexTask();
    print(result);
  },
  child: Text('Start Task'),
),


Step-by-Step Implementation of Isolates

For an isolate to work, the task it performs must be written outside any class. This ensures the task can run independently of the main UI thread:

int complexTask(int message) {
  int total = 0;
  for (int i = 0; i < 1000000000; i++) {
    total += i;
  }
  return total;
}


Spawning an Isolate

void runComplexTaskInIsolate() async {
  ReceivePort receivePort = ReceivePort();
  await Isolate.spawn(complexTaskIsolate, receivePort.sendPort);

  receivePort.listen((result) {
    print('Result: $result');
  });
}

void complexTaskIsolate(SendPort sendPort) {
  int result = complexTask(0);
  sendPort.send(result);
}



Implement assert() messages in Dart

Do you know that you can throw your message when your assert fails? assert() takes an optional message in which you can pass your message.


assert(title != null, "Title string cannot be null.");

Inconsistent JVM-target compatibility detected for tasks despite already defining jvm ver

Make sure you have the same version here:

compileOptions {
  sourceCompatibility = JavaVersion.VERSION_17
  targetCompatibility = JavaVersion.VERSION_17
}

kotlinOptions {
  jvmTarget = "17"
}


Add in your gradle.properties:

kotlin.jvm.target.validation.mode = IGNORE

Incorrect use of ParentData widget

The fix should be obvious once you know which parent widget is missing.


  • Flexible expected for Row, Column, or Flex
  • Expanded (a specialized Flexible) expected for Row, Column, or Flex
  • Positioned expected for Stack
  • TableCell expected for Table

Insecure HTTP is not allowed by platform

Add android:usesCleartextTraffic="true" to android/app/src/main/AndroidManifest.xml.

isLoading vsValueNotifier

Using ValueNotifier

class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final ValueNotifier<bool> isLoading = ValueNotifier(false);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Home Page")),
      body: ValueListenableBuilder<bool>(
        valueListenable: isLoading,
        builder: (context, loading, child) {
          if (loading) {
            return const Center(child: CircularProgressIndicator());
          }

          // Other content...
        },
      ),
    );
  }

  Future<void> _handleFunction(String id) async {
    isLoading.value = true;
    try {
      await databaseService.addToDatabase(widget.agentUid, routeId);
    } catch (error) {
      _alertService.showToast(text: 'Failed to add route.', icon: Icons.error);
    } finally {
      isLoading.value = false;
    }
  }
}


Using isLoading

class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool isLoading = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Home Page")),
      body: isLoading
          ? const Center(child: CircularProgressIndicator())
          : // Other content...
          Center(child: Text("Content goes here")),
    );
  }

  Future<void> _handleFunction(String id) async {
    setState(() {
      isLoading = true;
    });

    try {
      await databaseService.addToDatabase(widget.agentUid, routeId);
    } catch (error) {
      _alertService.showToast(text: 'Failed to add route.', icon: Icons.error);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }
}

Isolates

In Flutter, Isolates are used for concurrency to handle tasks that are computationally intensive without affecting the performance of the main UI thread. Here’s why you might use Isolates in Flutter:


  1. Prevent UI Blocking: Flutter uses a single thread (the main thread) for UI rendering and user interactions. If you perform heavy tasks, such as file I/O, complex calculations, or network requests on this thread, it can cause the UI to freeze. Isolates run on separate threads, allowing such tasks to be handled without blocking the UI.
  2. Parallel Processing: Isolates enable true parallelism in Dart. While Dart supports asynchronous operations using Future and async/await, these do not run on separate threads. Isolates, on the other hand, allow you to run multiple tasks in parallel by utilizing different CPU cores.
  3. Memory Isolation: Each Isolate has its own memory heap, which ensures that state is isolated between Isolates. This prevents issues like race conditions, making Isolates safer for certain types of concurrency.
  4. Performance: When handling tasks like image processing, data parsing, or machine learning model inference, using Isolates can improve performance because they allow you to utilize the full potential of multicore processors.
  5. Message Passing: Isolates communicate with each other using message passing (ports), which helps maintain the isolation of state while still enabling communication when needed.


Isolates are useful when you need to offload tasks that would otherwise slow down your app's responsiveness.

Issue with Flutter stating that CocoaPods is either not installed or in an invalid state

Verify CocoaPods Installation

Run the following command to check if CocoaPods is installed on your system:

pod --version


If CocoaPods isn't installed, use the command below to install it:

sudo gem install cocoapods


Update CocoaPods

If CocoaPods is outdated or misconfigured, update it using:

sudo gem install cocoapods --pre
pod setup


This ensures you have the latest version and proper setup.


Install CocoaPods in Your Flutter Project

Navigate to your Flutter project’s iOS directory and install dependencies:

cd ios
pod install


If you run into issues, update the local pod repository with:

pod repo update


Clean Your Flutter Project

Clear the Flutter cache and re-fetch dependencies:

flutter clean
flutter pub get


Then, reinstall iOS dependencies:

cd ios
pod install


Update Xcode Command-Line Tools

Ensure Xcode and its command-line tools are up-to-date by running:

sudo xcode-select --install


Run Flutter Doctor for Diagnostics

Run Flutter Doctor to check your system setup for any other issues:

flutter doctor


Follow any recommendations to fix potential problems.

Key Hash for Android-Facebook App

  1. Download OpenSSL from Google Code. (WIN32 for 32-bit machine & X64 for 64-bit machine)
  2. Go to C:/ and create a folder named OpenSSL.
  3. Extract it to folder OpenSSL.
  4. Open cmd.
  5. Type cd\ to go to C Drive.
  6. Type the command 1.
  7. If asking for password, put android.


Command 1

C:\>$ keytool -exportcert -alias androiddebugkey -keystore "C:\Documents and Settings\Administrator.android\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary |"C:\OpenSSL\bin\openssl" base64

Lazy Loading

class LazyLoadingList extends StatefulWidget {
  @override
  _LazyLoadingListState createState() => _LazyLoadingListState();
}

class _LazyLoadingListState extends State<LazyLoadingList> {
  final _scrollController = ScrollController();
  final _itemsPerPage = 10;
  var _loadedItems = 0;
  var _items = <String>[];

  @override
  void initState() {
    _scrollController.addListener(_scrollListener);
    super.initState();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _scrollListener() {
    if (_scrollController.offset >=
            _scrollController.position.maxScrollExtent &&
        !_scrollController.position.outOfRange) {
      _loadMoreItems();
    }
  }

  Future<void> _loadMoreItems() async {
    await Future.delayed(Duration(seconds: 1)); // simulate network latency
    setState(() {
      _items.addAll(_generateItems(_loadedItems, _itemsPerPage));
      _loadedItems += _itemsPerPage;
    });
  }

  List<String> _generateItems(int start, int count) {
    return List.generate(count, (index) => 'Item ${start + index + 1}');
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      controller: _scrollController,
      itemCount: _items.length + 1,
      itemBuilder: (context, index) {
        if (index == _items.length) {
          return Center(child: CircularProgressIndicator());
        } else {
          return ListTile(title: Text(_items[index]));
        }
      },
    );
  }
}

Local notification action button click not working

Add showsUserInterface: true

NotificationDetails(
  iOS: DarwinNotificationDetails(
    presentAlert: true,
    presentBadge: true,
    presentSound: true,
    interruptionLevel: InterruptionLevel.timeSensitive,
    categoryIdentifier: 'cat_1',
    badgeNumber: 0,
  ),
  android: AndroidNotificationDetails(
    'channel_notifs',
    'Local Notifications Channel',
    importance: Importance.max,
    priority: Priority.high,
    actions: [
      AndroidNotificationAction('action_1', 'Action 1', showsUserInterface: true),
      AndroidNotificationAction('action_2', 'Action 2', showsUserInterface: true),
    ],
    styleInformation: BigTextStyleInformation(
      action.text,
      contentTitle: action.title,
    ),
  ),
),