Introduction

After working for more than a year with Flutter, I have encountered a lot of problems and errors that I had to solve either by myself or by searching for solutions online, here is a list of the most common problems and useful tips that I have encountered while working with Flutter.

Most Common Problems

This section will cover the most common problems that I have encountered while working with Flutter and how to solve them, it will be updated regularly.

Note: You can contribute to this article by suggesting a change, i will be happy to review it and merge it.


IOS only 📱

CocoaPods not installed or not in valid state

Depending on your IDE, the problem is the same but the solution is different, often this is a problem with your IDE and not Flutter itself.

Note: You will need to do a full restart of your IDE after applying the solution, not just closing the window.

First, try to do the following:

sudo gem uninstall cocoapods && sudo gem install cocoapods

And restart your IDE.

If it doesn’t work, try to do the following:

open /Applications/Android\ Studio.app

If the command above doesn’t work, let’s try a fix for each IDE:

Visual Studio Code

flutter clean
flutter pub get
# Restart your IDE
flutter run

Android Studio

You will need to clean your cache.

To clear Android Studio’s cache and bring it out of its state of confusion, select ‘File > Invalidate Caches / Restart’ and then click the ‘Invalidate and Restart’ button. Clean and rebuild your project.

SocketException in MacOS

If you are using MacOS and you are trying to run your app involving network calls, you might encounter this error:

SocketException: Connection failed (OS Error: Operation not permitted, errno = 1), address =

To fix this issue, you need to add the following lines to macos/Runner/DebugProfile.entitlements and macos/Runner/Release.entitlements:

<key>com.apple.security.network.client</key>
<true/>

You can find more information about issue [here](to macos/Runner/DebugProfile.entitlements and macos/Runner/Release.entitlements)


Android only 🤖

minSdkVersion cannot be smaller than version xx declared in library

If you are using a third party library that requires a minimum SDK version that is higher than the one you are using, you might encounter this error, the fix is easy, you just need to update your minSdkVersion in your android/app/build.gradle file:

defaultConfig {
    ....
    minSdkVersion 20 //*** Change to the minimum SDK version required by your library
    ....
}

App requires Multidex support

This issue is related to the Android build only.

When writing large apps or making use of large plugins, you might encounter Android’s dex limit of 64k methods when targeting a minimum API of 20 or below.

The simplest way is to opt into multidex support when prompted. This will add multidex support to your app.

If for some reason the prompt doesn’t appear, you can add multidex support manually by following these steps:

  1. Open your android/app/build.gradle file.

  2. Add the following line as the last item in the defaultConfig block:

defaultConfig {
    ...

    multiDexEnabled true
}

SocketException in Android

If you are using Android and you are trying to run your app involving network calls, you might encounter this error:

SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 4444

To fix this issue, you need to add the following lines to android/app/src/main/AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>

All platforms 📱🤖💻

Null check operator used on a null value

If you are using null safety, you might encounter this error when using the exclamation mark also known as the bang operator (!) on a nullable variable or object:

To fix your issue you need to check your logs from the console and see which line is causing the problem

Once you have find it, you can fix it by one of the following solutions:

  • Check if the variable is null before using it:
if (myVariable != null) {
    // Do something
}
  • Use a null-aware operators like ?. and ?? to specify a default value:
myVariable?.myMethod() ?? defaultValue;

Another example:

int? a; // = null
a ??= 3;
print(a); // <-- Prints 3.

a ??= 5;
print(a); // <-- Still prints 3.

As you can see, the ?? and ?. are operators for dealing with values that might be null.

Keyboard overlapping form fields

If you are using a TextField or a TextFormField in your app, you might encounter this issue where the keyboard is overlapping the form fields, making it hard to see what you are typing.

To fix this issue, you need to wrap the form fields with a SingleChildScrollView widget:

SingleChildScrollView(
  child: Column(
    children: [
      // Your form fields
    ],
  ),
)

MissingPluginException

Some packages such as shared_preferences or url_launcher require you to add some configuration, but even with an hot restart, you might still encounter this error:

MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)

To fix this issue, you need to stop your app and run it again, meaning that you need to stop the app from your IDE and run it again.

At a last resort you can try to run flutter clean and flutter pub get and run your app again.

How to use hex color codes in Flutter

By default flutter offer a limited number of colors, and if you try to use your own color with an hexadecimale code, you might encounter an error since the Color class only accept integers.

To fix this issue you need to convert your hex color code to an integer :

1 - Remove the # from your hex color code

2 - Add 0xFF to the beginning of your hex color code

3 - Use the Color class to convert your hex color code to an integer

Color myColor = Color(0xFF000000);

More information about the Visibility widget can be found here.


Useful tips and tricks 🤯

This section will cover some useful tips and tricks that I have learned while working with Flutter, it will be updated regularly.

Note: You can contribute to this article by suggesting a change, i will be happy to review it and merge it.

What does the leading underscore mean in Dart?

Unlike Java, Dart doesn’t have the keywords public, protected, and private, instead it uses the leading underscore to indicate privacy, the leading underscore means that the variable or method is private, it can only be accessed from within the same library.

Note: There is no concept of “private” for local variables or parameters.

What is a library in Dart?

Every Dart file (plus its parts) is a library, think of it as shareable code base.

A Dart library can be a set of classes, constants, functions, typedefs, properties, and exceptions…

How to make a variable private in Dart?

By default, when you define a property for a class, it is public, meaning that it can be accessed from outside the class, but if you want to make it private, you need to add an underscore before the name of the property:

class MyClass {
  String _myPrivateProperty = 'Hello World';
}

This provide security and encapsulation, since it is now impossible to access the property from outside the class.

In Dart, privacy is at the library level rather than the class level. Adding an underscore to a variable makes it library private not class private.

How to format a date in Flutter

If you have a DateTime object it probably looks like this:

2021-08-12 11:25:11.000

This is not really readable, and might want to output something like this:

2021-08-12 – 11:25

To do that, you can use the DateFormat class from the intl package:

import 'package:intl/intl.dart';

DateTime now = DateTime.now();

String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);

Which will output the date in the format that you want:

2021-08-12 – 11:25

How to hide a snackbar programmatically in Flutter

For different reasons, you might want to hide a snackbar programmatically, to do that, you need to use the hideCurrentSnackBar method from the ScaffoldMessenger class:

ScaffoldMessenger.of(context).hideCurrentSnackBar();

Using this, you can hide the current or queued snackbar.

How to detect which environment (platform) the app is running on

The platform class from the dart:io package allows you to check which platform (Android, IOS, Mac…) the app is running on:

// Get the operating system as a string.
  String os = Platform.operatingSystem;
  // Or, use a predicate getter.
  if (Platform.isMacOS) {
    print('is a Mac');
  } else {
    print('is not a Mac');
  }

However, it doesn’t allow you to check if the app is running on the web, but you can check the answer to the question below to see how to do that.

How to check if the app is running on the web

Flutter comes with a Platform class that allows you to check the API for accessing platform-specific information, unfortunately it doesn’t have a method to check if the app is running on the web, but you can use the kIsWeb property from the foundation package to do just that:

import 'package:flutter/foundation.dart' show kIsWeb;

if (kIsWeb) {
  // Do something
}

How to create a number input field in Flutter

Flutter comes with a TextField widget that allows you to create a text input field, but it doesn’t have a number field, to overcome this issue, you can use the keyboardType property and set it to TextInputType.number:

TextField(
  keyboardType: TextInputType.number,
)

This will display a keyboard with numbers only on Android and IOS, but on the web, it will display a keyboard with numbers and letters, to fix this issue, you can use the inputFormatters property and set it to FilteringTextInputFormatter.digitsOnly:

TextField(
  keyboardType: TextInputType.number,
  inputFormatters: [FilteringTextInputFormatter.digitsOnly],
)

More can be found about the digitsOnly property here.

This will validate the input and only allow numbers, you should also validate the input on the backend to make sure that the user is not sending invalid data.

The TextInputFormatter class comes in handy when you want to provide as-you-type validation for a TextField, you can find more information about it here.

How to refresh the state of an AlertDialog in Flutter

If you ever tried to update the state of an AlertDialog without closing it, you might have seen that the state of the AlertDialog is not updated, only when you close it and open it again, the state is updated.

Flutter comes with a StatefulBuilder widget that allows you to do just that, it will rebuild the state of the AlertDialog without closing it.

await showDialog<void>(
  context: context,
  builder: (BuildContext context) {
    int? selectedRadio = 0;
    return AlertDialog(
      content: StatefulBuilder( // You need this, notice the parameters below:
        builder: (BuildContext context, StateSetter setState) {
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: List<Widget>.generate(4, (int index) {
              return Radio<int>(
                value: index,
                groupValue: selectedRadio,
                onChanged: (int? value) {
                  setState(() => selectedRadio = value);
                },
              );
            }),
          );
        },
      ),
    );
  },
);

How to remove the debug banner

If you are using the debug mode, a red banner will be displayed on the top right corner of your app, to remove it, you need to set the debugShowCheckedModeBanner property to false in your main.dart file:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false, // <-- Add this line
      title: 'My App',
      home: MyHomePage(),
    );
  }
}

How to delay the execution of a function in Flutter

In most languages, you can use the setTimeout function to delay the execution of a function, but in Flutter, you can use the Future.delayed function to do the same thing:

Future.delayed(const Duration(seconds: 1), () {
  print('One second has passed.'); // Prints after 1 second.
});

If the duration is 0 or less, it will execute the function immediately.

How to show/hide widgets programmatically in Flutter

The Visibility widget handle whether to show or hide a child within it, it has a visible property that you can set to true or false to show or hide the child.

Visibility(
  visible: true, // <-- Set to true to show the child
  child: Text('Hello World'),
)

More information about the Visibility widget can be found here.


I hope this article was helpful, if you have any question or suggestion, feel free to reach out to me on :

You can use my articles with no cost or attribution, feel free to edit them and make them your own.