Code Analysis & Linting in Flutter and Dart

One of the best practices that we introduced in the video best practices for Flutter is Flutter Code Analysis and Linting. I would like to start a small series of different Blog posts where we talk about each of these Best Practices and today we start with the very first one: Code Analysis and Linting.

Setup Code Linting for a Flutter project

In the beginning, let me say that additional Linting in Flutter is a controversial topic. On one side, many love code linting, because it allows us to focus on crucial parts of our code. However, some people are not fond of it because it restricts them and leads to false build errors. But before we start the discussion, let us begin with what code linting is and how we can use its full potential.

Code Linting is an automated verification that your code is correct. There is always a Linter that we all use in our day to day work. In editors like VSCode and Android Studio, we receive errors when our code is not runnable. The visualisation of build errors are already features of our Linter. This integrated Code Linter is a tool that checks your code for build problems, that means you would not even be possible to run your application. We do not have to search for errors in our code, and when everything is green, we are sure that our code is executable.

Thanks to modern tools, we can extend these rules and check our current project for more than just broken code. For example, we can tell our Linter that we want to check for wrong code styling. In Dart and Flutter the additional lint rules are managed by a file called analysis_options.yaml. If you have never heard about a yaml file extension, it is just a convenient way to structure a file that allows you to create tree structures with two spaces. Feel free to read more about the .yaml file extension here.

Our Mission: Enforce single quotes in our project

Let us assume we would force all our developers to work on our project, that every string should be done with a single quote. Our IDE should show it immediately, like in the image below.

Example of our result

To achieve that the static code analyzer of Dart and Flutter recognize that mistake, we must create an analysis_options.yaml responsible for our whole project gives our Dart analyzer instructions that run in the background and verifies our code. We can create the analysis_options in the root of our project, and most IDE’s like Android Studio or Visual Studio Code will right away understand what it needs to do with it. Now, let’s take a closer look into the analysis_options file. Inside of the analysis_options, we can modify the behaviour of the analyzer and the linter.

The Analyzer & Linter

In our first section in the common analysis_options.yaml file is usually the analyzer. Here we can configure a more general part of how we want to check our code. Firstly, we can set up if we want to show errors, warnings, or as information for specific rules. Secondly, we can exclude files and folders from the checking system. Moreover, we can ignore specific rules. Last but not least, we have the chance to introduce additional strict type checking and experimental behaviour like no slow checks or super-mixins.

To use now the main information that we registered to the Analyzer, we have to specify the rules that we want to apply in our project. Therefore, we use the Linter section of the analysis_options.yaml. In the linter section, we define which rules are applied to our project. There are around 180 rules that you can specify and make them right away visible in your application. To explain, all of them would bust this blog post, so feel free to look at the list of linting rules you can specify at the Linter for Dart site.

Linting Rules

At the time I write this post, there are three different categories of Linting Rules. The first is the Error Rules, and they are possible coding errors. Secondly, we have the Style Rules that define code style matters, like a single quote or double quote. It does not hint whether your code is stable or not, but it helps align the whole codebase. The pub rules follow both. This set of rules defines how a pub package has to behave; it includes only two rules on how to name a package and sort dependencies in your pubspec.yaml.

avoid_init_to_null

As the name already states with this linter rule, you do not allow anymore to initialize a variable with null. But why could this be helpful? In Dart, every variable that is not specified with a value is automatically set to null. There is no concept of empty memory or any other trap that we could fall into. With that in mind, a specific declaration of a variable to null would only bloat our code and is unnecessary and unneeded.

Lint Rule of avoid init to null
On explicit null decleration the linter is showing a message

use_string_buffers

Another fantastic rule that many developers are not really aware of is a more performant way to concatenate strings. The String Buffer helps you improve the concatenation of Strings and allows you to do it in the most performant way. To make sure that all contributors in your code concatenate strings efficiently, we can set the use_string_buffers style rule.

Lint Rule: Use String Buffers Example
Linter shows a warning if you could use a StringBuffer
Lint Rule: Solution to Use String Buffer
StringBuffer provides a performant way to handle Strings

prefer_double_quotes

The prefer double quotes rule allows you to take control if you want to enforce a specific quote style. Here we prefer in our code base double quotes but also the single quote rule exists and makes it possible to enforce quote style. This is especially helpful if you work in a multilanguage team because Keyboard layouts differ from country to country. In contrast, in English and American speaking country, the single quote is easier accessible and mostly used in other countries like Germany, the double quote is usually prefered. This rule leads to clear information on how the maintainer or the owner of a package or project wants to work in general.

Linting Rule: Prefer Double Quotes
The prefer double quotes Rule lead to informations about usage of a double quote

This is also the rule that we will use to finally solve our problem and enforce double quotes for the whole project.

The Solution

Alright now that we know how the Linter and the Analyzer work lets solve our goal for this blog post, we want to enforce every developer who works on our codebase to prefer double quotes, and if they do not, we want to really show it as an error. The first thing we have to do is to define the Analyzer with the correct severity of the issue. In our case, this would be “error”. Next, we just defined in the pubspec.yaml our linter with the new rule that we want to add.

Analyzer & Linter

Now after we have specified the rule and the severity of the enforcement we can already see in our IDE the errors appearing.

Linting error appear after setting the right rules

If we now run dart analyze in our terminal inside our project, we receive a full analyzing report. Now we can use this command inside our terminal. If we use this command now in our CI / CD chain, the build will fail, and our team would have to fix it to merge it in our project.

Lint Rules as a package

As always, there are fantastic packages that come with a predefined selection of rules that makes it easier to set up the first baseline that you want to use in your project. Let us first have a look at how we can include them in our project.

Install a third party linting rule set

In order to add a linting rule set we have to first add the dependency to the pub.dev package in our pubspec.yaml. As an example we want to add the Lint package to our project.

Adding lint into our dev dependencies

The next step is to import the rules from the package into our analysis_options.yaml.

Added the analysis_options of the lint package to our analysis_options of the project

As soon as you open now the different files, you will now recognize that the package’s linting rules are already taken into account and are ready to use. Let us assume that you do not like a rule. You can easily overwrite the behaviour by including the linter and analyzer. Your rules will overwrite the package’s rules, with that you will always have control over the linting.

Analysis Option to add linting to your project
Full solution with overwrite of specific rules

Lint Package

The lint package logo
Logo of the Lint Package

Pascal Welsch creates the first Lint package, and it includes a baseline of lint rules for Flutter and Dart Projects. You can extend or exclude rules afterwards if you use this package, but it is created with consumers. That means if you are not necessarily working on the Flutter project. This should be your way to go.

Pedantic

The second package that I want to introduce you is the so-called pedantic package. The Flutter team created the pedantic package to support a set of rules that is usually way more restrictive in terms of usage and allowances and is a bit over-engineered from time to time.

Conclusion

In this post, we learned how to use the Linting Rules to our advantage and enforce rules so that every developer who collaborates with us works in the same way. To generate these rules and discuss them in a team could be tedious, and many people would say that it is not worth the effort. But if the conversation and discussion start now, you have the right tools to join the discussion and give some valuable insights.

Thank you for reading and let me know what you are thinking about Linting rules down in the description below!

Max Weber

A passionate Software Engineer for more than six years in different industries. He worked as a consultant for multiple enterprise companies in Europe such as Swisscom, Diligent and Deutsche Telekom. In 2020 he founded Flutter Explained a Tutorial Channel on YouTube where he explains everything around Flutter Development.

This Post Has 73 Comments

  1. WayneCep

    [url=https://umbria-traveller.com] world cuisines
    [url=https://umbria-traveller.com] food art
    [url=https://umbria-traveller.com] festive dishes
    [url=https://umbria-traveller.com] types of dishes
    [url=https://umbria-traveller.com] diet food
    [url=https://umbria-traveller.com] cooking
    [url=https://umbria-traveller.com] diets & weight Loss

  2. TerryNen

    [url=””].[/url]

  3. MarcoInvem

    You received a money transfer of $ 89.44! PREPAYMENT! To receive funds, go to the payment page
    [url=http://5.79.219.166:8080/work/drac/]Detail[/url]: [url=http://5.79.219.166:8080/work/drac/]Official bank site/url] Official bank site Official bank site

  4. Tristanlaf

    Pjidfhisofkcwspfjowfkpwlfpjwofk rwkfpwkgowjkfwjgoowfkpwg
    Nifhfeidfjwofjowhfie jfjeofwofjwoefjwoj irwojdwohfiewjfowfie
    Mcniscswhfuhicfj ijfwokfdwhfiwjbskgk gnrejgbskesghegnr gkejgejgj
    Ojffsfjhnwsfjebgejfwjfiehi jiffniehfshiufhaeifnjskgehiwuw fjefje
    Ojbcjdhswv bjwksbdhwjsvdhfwjb jbfjksafbejfbejfbejbcsufuj
    Gjsbjfcwhdnwdwhnfw hiwshfjabhfewbfjekb fuabfiuebfbcdsjfbewiufbeh
    https://oituryufhcnjdjqajdsfsjk.com
    KdwyeuuiwiosIBHBCFDHKFJJ FJKBJKWFJFBHEAKNDSJAKFGBSHFAWJDJESBG

  5. skyreverylib

    [url=https://www.skyrevery.com/destinations/private-jet-bern/]Bern Private Jet Charter [/url] – more information on our website [url=https://skyrevery.com]skyrevery.com[/url]
    [url=https://skyrevery.com/]Private jet rental[/url] at SkyRevery allows you to use such valuable resource as time most efficiently.
    You are the one who decides where and when your private jet will fly. It is possible to organize and perform a flight between any two civil airports worldwide round the clock. In airports, private jet passengers use special VIP terminals where airport formalities are minimized, and all handling is really fast – you come just 30 minutes before the estimated time of the departure of the rented private jet.
    When you need [url=https://skyrevery.com/]private jet charter[/url] now, we can organise your flight with departure in 3 hours from confirmation.

  6. MothCealm

    [url=https://hqd.wiki/]hqd несовершеннолетним[/url]

    электронная сигарета плюсы и минусы

  7. SmithNen

    Sputnik V vaccination has begun in Slovakia. The provisioning of the Russian vaccine to the homeland was accompanied penny-pinching a civic slight and led to the abandonment of Prime Helpmate of the cloth Igor Matovich and a realignment of the government. As a result, the motherland received the Russian vaccine, in defiance of the taking place that neither the European regulator nor the WHO has furthermore approved it.
    In neighboring Hungary, which approved the fritter away of Sputnik in February as the beginning in Europe, more than 50% of the grown up commoners has already been vaccinated; in Russia – a under age more than 10%. In Slovakia, five thousand people signed up in place of the Sputnik vaccination.
    I, as a person not young, very rarely used blogs, considering them useless, but now I completely changed my mind by visiting this wonderful blog. Firstly, I liked the accessible interface and easy navigation, and secondly-a huge amount of useful information that will be useful to me in my profession for sure. Now I will visit blogs much more often, and I will add this one to my bookmarks for convenience. A sufficient number of reviews were also collected, which indicates an excellent administration. Thank you so much for opening my eyes. I will be your constant satisfied a user.. You can impute to another article on this area of study at this tie-up [url=”https://cykelgear.rabatter.site”]https://garnstudio.rabatt.fun[/url]

  8. Raymundo

    I savour, cause I discovered exactly what I used to be looking for.

    You have ended my 4 day lengthy hunt! God Bless you man.
    Have a nice day. Bye

  9. Shanna

    Hey there! This is my 1st comment here so I just wanted to give a quick shout out and say I truly enjoy reading your posts.
    Can you suggest any other blogs/websites/forums that cover
    the same subjects? Thank you!

  10. id akaun test ntc33

    Wow, that’s what I was exploring for, what
    a data! present here at this website, thanks admin of this website.

    Feel free to surf to my page id akaun test ntc33

  11. 918kiss tips

    If some one needs expert view on the topic of blogging after that i propose him/her to visit this web site, Keep up the good job.

    Visit my site – 918kiss tips

  12. Jimmie

    Thank you for some other informative website.
    The place else may I am getting that kind of info written in such
    a perfect method? I have a venture that I am simply now working on, and I have been on the glance out for such information.

    Also visit my webpage: game greatwall99 online [Jimmie]

  13. Hello colleagues, its wonderful post concerning cultureand fully defined, keep it up all the time.

  14. Hmm is anyone else having problems with the pictures on this blog loading?
    I’m trying to figure out if its a problem
    on my end or if it’s the blog. Any suggestions would be
    greatly appreciated.

  15. 918kiss-m.com

    It’s very straightforward to find out any matter on net as compared to textbooks,
    as I found this piece of writing at this website.

    My web-site :: 918kiss plus download (918kiss-m.com)

  16. kiosk ok388

    I’m not that much of a internet reader to be honest but your blogs really nice,
    keep it up! I’ll go ahead and bookmark your website to come back
    later on. All the best

    Here is my web page … kiosk ok388

  17. Do you mind if I quote a couple of your posts as long as
    I provide credit and sources back to your weblog?
    My website is in the very same niche as yours and my visitors would really benefit from
    a lot of the information you provide here. Please let me know if this
    okay with you. Thank you!

  18. I always emailed this blog post page to all my associates, because if like to read it then my contacts will too.

  19. Fantastic goods from you, man. I’ve understand your stuff previous to and you’re just too magnificent.
    I really like what you have acquired here, certainly like what you’re saying and the way in which
    you say it. You make it enjoyable and you still care
    for to keep it wise. I cant wait to read far more from you.
    This is actually a terrific site.

  20. Amazing blog! Do you have any tips for aspiring writers?
    I’m planning to start my own site soon but I’m
    a little lost on everything. Would you recommend starting with a free platform like WordPress
    or go for a paid option? There are so many options out there that I’m totally overwhelmed
    .. Any suggestions? Cheers!

  21. Have you ever thought about adding a little bit more than just your articles?
    I mean, what you say is important and everything.

    Nevertheless imagine if you added some great visuals or video clips to
    give your posts more, “pop”! Your content is excellent but with images and clips, this site could certainly be one of
    the greatest in its niche. Very good blog! https://tinilink.com/trmedyaco977422

  22. It’s an remarkable article designed for all the internet users; they
    will obtain advantage from it I am sure.

  23. I have read so many articles or reviews about
    the blogger lovers except this post is really a pleasant post, keep it
    up.

  24. Oh my goodness! Awesome article dude! Thanks, However I am encountering troubles
    with your RSS. I don’t know why I can’t join it. Is there anyone else having identical RSS problems?

    Anyone that knows the solution will you kindly respond?
    Thanx!!

  25. Thank you for sharing үour thoughts. I really appreciate your efforgs аnd I wioll be waiting for your next ѡritе ups
    thank you once again.

  26. mpc-install.com

    As a Newbie, I am constantly searching online for articles
    that can aid me. Thank you

    Stop by my page Breeze Box AC Review (mpc-install.com)

  27. Thank үou for the good writeup. It in fact was a amusement account it.
    Look ɑdvanced to far added ɑgreeable fr᧐m you! By the waү, how can we commսnicate?

  28. jual rumput sintetis

    Тhere’s definately a great ddal to learn about this issue.

    I lіke all the рoints you’ѵemade.

  29. Tоdаy, while I was at work, mʏу sister stole my iPad and tested to see if it cɑn survive a 25 foot drop, just
    so she can be a youtube sensation. My аpple ipad is now destroyed and she has 83 views.
    I know this is entirely off topiϲ but I hhad to ѕhare it with someоne!

  30. Diana

    Touche. Great arguments. Keep up the amazing work.

    Also visit my website … Mountain Pure CBD [Diana]

  31. www.qijiang520.com

    wonderful points altogether, you simply received a new reader.
    What may you recommend in regards to your publish that you just made a few days in the past?

    Any positive?

    My website: Keto Hack Pills – http://www.qijiang520.com,

  32. mpc-install.com

    Hello there, just became alert to your blog through Google,
    and found that it’s truly informative. I?m going to watch out
    for brussels. I?ll appreciate if you continue this in future.
    Lots of people will be benefited from your writing. Cheers!

    Also visit my homepage … BreezeBox Portable AC Reviews (mpc-install.com)

  33. I enjoy what you guys are up too. This kind of clever work and reporting!
    Keep up the very good works guys I’ve incorporated you guys to our blogroll.

  34. www.fles.hlc.edu.tw

    hey there and thank you for your info ? I have definitely picked up something new from right here.

    I did however expertise several technical issues using
    this website, since I experienced to reload the
    website lots of times previous to I could get it to load properly.
    I had been wondering if your hosting is OK? Not that I’m complaining,
    but sluggish loading instances times will often affect your placement in google and can damage your high-quality score if ads
    and marketing with Adwords. Well I?m adding this RSS to my e-mail and can look out for much more of
    your respective fascinating content. Ensure that you update this
    again soon..

    Look into my site – XTRM Life Keto (http://www.fles.hlc.edu.tw)

  35. anapa-alrosa.com.ru

    I like the helpful information you provide in your articles.
    I’ll bookmark your weblog and check again here frequently.
    I’m quite certain I’ll learn a lot of new stuff
    right here! Good luck for the next!

    my blog: Zenzi CBD; anapa-alrosa.com.ru,

  36. www.adult.uk.com

    Hi there this is somewhat of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code
    with HTML. I’m starting a blog soon but have no
    coding knowledge so I wanted to get advice from someone with experience.
    Any help would be greatly appreciated!

    My website Zenzi CBD Review [http://www.adult.uk.com]

  37. ternak hewan

    Fantastic wеbsite you have here but I was curious about if you knew of any community forums that cover the same
    topucs talked about in tһis article? I’Ԁ really love to bе a part
    οf community where I can get feed-back from other knowleɗgeаble people that share the same interest.
    If yߋuu have any sᥙggеstions, please let me know. Many thanks!

  38. Thank you a lot for sharing this with all people you
    really understand what you are speaking approximately! Bookmarked.

    Please additionally consult with my website =). We will have a
    hyperlink change agreement between us

    Feel free to visit my web site Keto Burn Advantage (watchmoviesonlinenow.org)

  39. You really mаke it appeaг really easy together with your presеntation however I find this matter to
    be really sօmetһing that I feel I mіght by nno mans understand.

    It kind of feels too complex and very extensive foor me.
    I’m lоkking ahead for your nest put up, I will tryy to get the hang of it!

  40. mpc-install.com

    Thanks for sharing superb informations. Your site
    is very cool. I am impressed by the details that you have on this blog.
    It reveals how nicely you perceive this subject.
    Bookmarked this website page, will come back for extra articles.
    You, my friend, ROCK! I found just the information I already searched everywhere and just could not come across.
    What an ideal site.

    Feel free to visit my web blog; TechPro Wifi Booster (mpc-install.com)

  41. http://www.aniene.net

    Aw, this was an extremely good post. Taking the time and
    actual effort to create a really good article?
    but what can I say? I hesitate a lot and never seem to get anything done.

    Feel free to visit my page: XTRM Life Keto Ingredients (http://www.aniene.net)

  42. ahli hewan

    Write more, thats аll I have to say. Liteгally, it seems ɑas thoᥙgh
    yyou relied on the video to make your point. You obviously know
    what youre talking aboսt, ѡhy waste your intеlliցence on just posting videοs to your blog ѡһen you couⅼd be giving uѕs ѕomething infgormative to read?

  43. jasa backlink pbn

    Hіyа! I know this is kinda offf toρic however I’d figured I’d ask.
    Would you bee іnterested in trading links or maybe guest authorіng a blⲟg article or vice-versa?
    My sitе ⅾiscusses a lot of the same topics
    as yourѕ and I think we could greatly benefit from each other.
    If you might be interested feеl free to shoot me an e-mail.
    I look forward to hearing from you! Awesome blоg by the
    way!

  44. 163.30.42.16

    Thanks for some other wonderful article.
    Where else could anyone get that type of info in such an ideal way of
    writing? I’ve a presentation subsequent week, and I am at
    the search for such information.

    Feel free to visit my blog – Zenzi CBD (163.30.42.16)

  45. jasa backlink pbn

    Ꭰo you mind іf I գuote a few off your articles ɑs long as
    I provide credit and sources back to your weblog?
    My blog is in the exact same niche as yours and my users would genuinely
    benefit from a lot of thhe information yyou prоvide hеre.
    Pleasе let me know if this alright wuth you. Apρreciate іt!

  46. mpc-install.com

    Every weekend i used to go to see this web site, for the reason that i wish for enjoyment, as this this website conations genuinely fastidious funny stuff too.

    Feel free to visit my web-site … Zenzi Hemp Gummies (mpc-install.com)

  47. My Ьrother ѕuggested I might like thіs weeb site.
    He waѕ totally right. This post actսally made my day.
    You can not imagine just hoѡ muϲh timе I hɑd spent for thijs info!
    Thanks!

  48. Hi, its fastidious post concernnց media print, we all Ьe familiar wirh media
    is a impressive source of facts.

  49. www.mangguoty.com

    Hello just wanted to give you a quick heads up. The words in your
    post seem to be running off the screen in Ie. I’m not sure
    if this is a format issue or something to do with browser compatibility
    but I figured I’d post to let you know. The design look great though!
    Hope you get the problem solved soon. Cheers

    Here is my web page PremiumShot Keto, http://www.mangguoty.com,

  50. www.qijiang520.com

    Its like you read my mind! You seem to know a lot about this, like you wrote the book in it or something.
    I think that you could do with some pics to drive the message
    home a little bit, but instead of that, this is magnificent blog.
    A fantastic read. I’ll certainly be back.

    Visit my site … Male Enhancement PM (http://www.qijiang520.com)

  51. Hi there, just became alert to your blog through Google,
    and found that it is truly informative.
    I am gonna watch out for brussels. I will appreciate if you continue this in future.
    Many people will be benefited from your writing. Cheers!

    my homepage; Male Enhancement XR (sheriffptacentral.co.za)

  52. Thanks on your marvelous posting! I actually enjoyed reading
    it, you will be a great author. I will make certain to bookmark your blog and definitely will come back at some point.
    I want to encourage yourself to continue your great posts, have a nice
    day!

    My web blog – Mountain Pure CBD Review, https://mpc-install.com/,

  53. Anke

    It’s actually a nice and helpful piece of info. I’m happy that you just shared this helpful information with us.
    Please keep us up to date like this. Thanks for sharing.

    Here is my page: Breeze Box AC (Anke)

  54. www.fotosombra.com.br

    I just wanted to thank you yet again for that amazing blog you have developed here.
    It truly is full of useful tips for those who are truly interested in that subject, especially this very post.
    Your all so sweet and also thoughtful of others and reading the blog posts is a
    superb delight if you ask me. And what a generous treat!
    Mary and I will certainly have excitement making use of your
    suggestions in what we have to do in the near future.
    Our checklist is a distance long and simply
    put tips will definitely be put to beneficial use.

    Also visit my webpage :: Living Tree CBD (http://www.fotosombra.com.br)

  55. Greetings! Very helpful advice in this particular post!
    It is the little changes that produce the largest changes.

    Many thanks for sharing!

  56. Link exchange is nothing else however it is only placing the other person’s weblog link on your page
    at appropriate place and other person will also do similar in favor of you.

Leave a Reply