r/FlutterDev • u/Shuvojit007 • May 08 '20
Article 18+ Flutter tips & tricks
If you want to produce (or reproduce) a production ready flutter app, we have 18+ tips and tricks for you. π
1. Create Intro Screen in Just 10 Minutes
If you need an awesome intro screen but donβt have an awesome idea, Introduction Screen will save you. You'll be amazed.
2. Use Flutter Snippet
If you need productivity, Flutter Code Snippet will make you a superstar. You can easily create commonly used Flutter classes and methods. For example, you can create StreamBuilder Widget or SingleChildScrollView Widget by typing the shortcut streamBldr and singleChildSV respectively. You can use the flutter snippet in Android Studio or VSCode.
3. Create Mind-blowing Icons Using Font Awesome
You donβt have to be the designer to include mind-blowing icons in your app. Just use the font awesome for flutter and you will create magic in minutes.
4. Enjoy Dependency Magic Using get.it
A good practice is to put your appβs logic in classes separated from your Widgets and then inject it wherever needed. For example, one of my app, we need to access the Prefmanger class from multiple places to read and update the user state stored in the localstorage. We used get_it so that this class can be injectable as a dependency.
GetIt locator = GetIt.instance;
void setupLocator() async {
var instance = await PrefManager.getInstance();
locator.registerSingleton<PrefManager>(instance,signalsReady: true);
FirebaseDatabase database = FirebaseDatabase.instance;
database.setPersistenceEnabled(true);
Locator.registerSingleton<DatabaseReference>(database.reference());
}
//Now you can easily access our prefmanger class like below:
locator<PrefManager>().color = 12 ;If you want to see the code block properly, please check out the full article on our Medium blog.
5. Reuse Data Using the Singleton Pattern
Singleton means the class has only one instance and also provides a global point of access to it. It is also an easy one to get wrong if you are not using it carefully. We need to access our ThemeColorclass (dark mode or light mode) again and again to set our theme color in widget . π
class ThemeColor{
// Singleton instance
static final ThemeColor _repo = new ThemeColor._();
// Singleton accessor
static ThemeColor get instance => _repo;
// A private constructor. Allows us to create instances of Repository
// only from within the Repository class itself.
ThemeColor._();
Color cardColor(){
return locator<PrefManager>().darkTheme? Color(0xff221F47):Colors.white;`
}
Color containerColor(){
return locator<PrefManager>().darkTheme? Color(0xff161430):Colors.white;`
}
}
ThemeColor.instance.cardColor()6. Avoid Widget Rebuild by Using const Constructor
If you want to prevent unwanted widget rebuilds always use const constructor. In the code below, the instance of BoxDecoration will remain the same even if the setState is called.
Container(
width: 250,
height: 250,
decoration: const BoxDecoration(
borderRadius: BorderRadius.only(
bottomLeft: const Radius.circular(30.0),
bottomRight: const Radius.circular(30.0))),
child:.....
);7. Code Format Using dartfmt
Always add Trailing Commas (,). It will help you to format your code by using dartfmt. After that you will be able to get rid of the headache of formatting by using dartfmt.
8. Write Cleaner Code Using the Spread Operator
The Dart 2.3 introduced a few useful features and one of them I like is the Spread operator. This is very useful when you need conditional UI widgets. Specially when you have nested conditional UI Widget.
Stack(
alignment: Alignment.center,
children: <Widget>[
if (_visible) ...[
spaceAnim(),
//Nested if-else
if (_visible) ...[
spaceAnim(),
]else ...[
galaxyAnim(),
],
]else ...[
galaxyAnim(),
],
],
),9. Custom Extension to Reduce Duplicate
Donβt make your code wet π. Keep it DRY. Here the word DRY meansβββDonβt Repeat Yourself. Hence, you should not repeat the same functionality in multiple places.
In my app, I need to convert HTML tags to be displayed on the UI because mighty Flutter is still reluctant to support HTML tags. And, we needed to repeat the code below in several places. That's why I created an extension method that can be used anywhere needed.
String get renderHtml {
return this
.replaceAll(β β, β β)
.replaceAll(β β, β β)
.replaceAll(β β, β β)
.replaceAll(β<br>β, β\nβ)
.replaceAll(β<br/>β, β\nβ)
.replaceAll(β<β, β<β);
}10. Less Code Using Double Dot, The Cascade Operator
Dart has a single dot (.) operator. And a few minutes ago, we talked about three dots (β¦) . So, one and three dots are covered. Do you feel like anything missing in the middle? You got it correctly. We are talking about the middle person, the double dot (..) which is also known as the cascadeoperator.
You can use the cascade operator to save typing time when multiple method calls on the same object are being made.
11. Knock Out the iPhone Notch with Safe Area
Itβs a pain that some of your content is getting cut by the iPhone 10+ notch. The same could happen in Android.
Consider using the SafeArea widget can keep the pesky notification bars and phone notches from encroaching on your appβs UI. It uses a MediaQuery to check the dimensions of the screen and pads its child Widget to match, making sure your app is safe on both iOS and Android!
12. Use Key for Efficient ListView Rendering
To make rendering efficient, use keys on each item. This will make your list view rendering very efficient.
13. Efficient Debugging with Performance Overlay
Performance Overlay shows how long each frame took to build and at the top there is the GPU time (Raster Thread) and at the bottom is Ui Time (Ui Thread). If you see a red bar in the UI graph, the Dart code is too expensive. If a red vertical bar appears in the GPU graph, the scene is too expensive to render.
14. Avoid Profiling in the Debug Mode
You will not get accurate performance indication if you profile in the debug mode. Debug mode is by default much slower than production mode. Simulator/ Emulator is not indicative of how your app actually works in Real Device.
15. Use Tracing to Measure Execution Time
You might not know how much time you took to finish your job in the bathroom. However, you can use the Tracing to see how much time is taken to execute.
void DoSomeThing(){
Timeline.startSync(βDoSomeThingβ);
// Write your code
Timeline.finishSync();
}16. Declare Multiple Variables with Shortcut Usually, I declare my variable most of the time this way
int mark = 10;
int total = 10;
int amount = 10;But if you are lazy like me than you can also do these things this way
int mark =10,
total = 20,
amount = 30;17. Smart Logging, Log Anything
Though we are used to log the string message, we can also pass other objects like List, Map, or Set. For more about log level, logPrinter, logOutput, checkout the logger doc.
18. Set Cross-Platform Icons Like a Pro
Are you messed up to set icons for both the Android and the iOS version of your app? Donβt worry, I will give you two steps to handle it using the Flutter Launcher Icon. First, setup your config file.
dev_dependencies:
flutter_launcher_icons: "0.7.3"
flutter_icons:
android: "launcher_icon"
ios: true
image_path: "assets/icon/icon.png"
Then run the package.
flutter pub get
flutter pub run flutter_launcher_icons:main18+. Get That Level Powered by Basic Utils
Do you need extra power in some crucial moments? Consider using basic_util. It contains a list of amazing methods to give you productivity at the right time. For more utils like SortUtils, ColorUtils, DateUtils, IterableUtils, CryptoUtils, HttpUtils in the basic utils.
Let me know the tips & tricks that you discovered while developing your flutter app.
6
May 08 '20
Thank you for this list. I am new to Dart and Flutter, these tips are really helpful to me
4
2
u/jhankarMahbub May 08 '20
Very good list. Thanks for sharing this with us. These are very helpful.
1
2
2
2
u/natanevangelista May 11 '20
Great tips, especially the const constructor thing. Thanks for sharing!
2
14
u/Elixane May 08 '20
Markdown formatting, which Reddit uses, supports including code snippets. All you have to do is indent by four spaces for blocks of code, or `surround in backticks` for code in the middle of a sentence. (If the code you want to surround includes a backtick, use ``two backticks (`)``).
<p class='example'>
code indented by four spaces displays like this
</p>This makes things like line breaks in code appear like they're supposed to, puts it in a nice monospace font, and makes sure that things that would otherwise be interpreted as Markdown formatting aren't.
12
3
u/mycroftholmess May 08 '20
Thanks! I'm sure everyone can learn a thing or two from this list at the very least
3
2
2
u/p_karim May 08 '20
Wow, the title only already shows how powerful the tips & tricks will be. π
By the way, it's the best and the most informative post I found on Reddit till now β so perfectly explained. Hats off to the author. ππ»
2
2
1
u/bartturner May 09 '20
Really good stuff. Thanks for taking the time.
Personally really love Flutter. Been a while since really enjoyed using a new tool for development.
Flutter just fits with how my brain works.
1
1
u/Randormi Jun 06 '20
Been building with flutter for over a year now, and this post is amazing, learned a lot! (especially conditional children for widget) thank you sir!
Do you use AppCenter for testing? We're having hard time waiting for test flight beta review
2
47
u/dljens May 08 '20
Aw, was hoping for R-rated app tips :O