Software Development

Dealing with "NoSuchMethodError: The method '[]' was called on null" in Flutter?

CH Asked by Charles Moore · 18-11-2023
0 upvotes 12,432 views 0 comments
The question

I'm frequently hitting this error when trying to display data from a JSON API. I've checked my model classes and they look correct, but occasionally when the network is slow or the API returns a null field, the whole UI crashes with a red screen. How do I properly implement null safety in 2024 to make my UI resilient to unexpected backend changes?

3 answers

0
MA
Answered on 20-11-2023

This error usually means you're trying to access a key on a Map that doesn't exist or the Map itself is null. With Dart's sound null safety, you should be using '?' or '??' operators. For example, 'data?['name'] ?? "Default Name"'. However, the best practice I implemented in 2023 was moving to 'json_serializable' or 'freezed'. These packages generate the boilerplate for you and allow you to define default values if a field is missing from the JSON, which prevents the UI from ever receiving a 'null' that it doesn't expect.

0
RI
Answered on 21-11-2023

Have you tried wrapping your main widget tree in an 'ErrorWidget.builder'? It won't stop the null, but it will prevent the "Red Screen of Death" for your users in production.

CH 23-11-2023

Richard, I actually did implement a custom error widget, but it’s more of a band-aid. The real issue is my model logic. I'm doing a lot of 'dynamic' typing because the API is inconsistent. Should I be using a more strict schema-first approach? I've heard 'freezed' is good for this, but I was worried about the extra build_runner time it takes during development. Does it really save that much time in the long run?

0
EL
Answered on 24-11-2023

Always use a 'FutureBuilder' or 'StreamBuilder' and check 'snapshot.hasData' before trying to render anything. This is the most basic way to avoid calling methods on null.

MA 25-11-2023

Exactly! Elizabeth's advice combined with Mary's suggestion of using a library like 'freezed' will make your app virtually crash-proof regarding data inconsistencies.

Share your thoughts

Your email address will not be published. Required fields are marked (*)

Professional Counselling Session

Still have questions?
Schedule a free counselling session

Our experts are ready to help you with any questions about courses, admissions, or career paths. Get personalized guidance from industry professionals.

Request a Call Back

Search Online

We Accept

We Accept

Follow Us

"PMI®", "PMBOK®", "PMP®", "CAPM®" and "PMI-ACP®" are registered marks of the Project Management Institute, Inc. | "CSM", "CST" are Registered Trade Marks of The Scrum Alliance, USA. | COBIT® is a trademark of ISACA® registered in the United States and other countries.

Book Free Session