What is a NoSuchMethod error and how do I fix it?

▼魔方 西西 提交于 2020-12-15 05:45:29

问题


I have some code and when I run it produces an error, saying:

NoSuchMethod: the method 'XYZ' was called on null

What does that mean and how do I fix it?


回答1:


Why do I get this error?

Example

As a real world comparison, what just happened is this conversation:

Hey, how much gas is left in the tank of the car?

What are you talking about, we don't have a car.

That is exactly what is happening in your program. You wanted to call a function like _car.getGasLevel(); but there is no car, the variable _car is null.

Obviously, in your program it might not be a car. It could be a list or a string or anything else really.

Technical explanation

You are trying to use a variable that is null. Either you have explicitly set it to null, or you just never set it at all, the default value is null.

Like any variable, it can be passed into other functions. The place where you get the error might not be the source. You will have to follow the leads from the actual null value to where it originally came from, to find what the problem is and what the solution might be.

null can have different meanings: variables not set to another value will be null, but sometimes null values are used by programmers intentionally to signal that there is no value. Databases have nullable fields, JSON has missing values. Missing information may indeed be the information itself. The variable bool userWantsPizzaForDinner; for example might be used for true when the user said yes, false when the user declined and it might still be null when the user has not yet picked something. That's not a mistake, it's intentionally used and needs to be handled accordingly.

How do I fix it?

Find it

Use the stack trace that came with the error message to find out exactly which line the error was on. Then set a breakpoint on that line. When the program hits the breakpoint, inspect all the values of the variables. One of them is null, find out which one.

Fix it

Once you know which variable it is, find out how it ended up being null. Where did it come from? Was the value never set in the first place? Was the value another variable? How did that variable got it's value. It's like a line of breadcrumbs you can follow until you arrive at a point where you find that some variable was never set, or maybe you arrive at a point where you find that a variable was intentionally set to null. If it was unintentional, just fix it. Set it to the value you want it to have. If it was intentional, then you need to handle it further down in the program. Maybe you need another if to do something special for this case. If in doubt, you can ask the person that intentionally set it to null what they wanted to achieve.



来源:https://stackoverflow.com/questions/65104524/null-error-when-selecting-a-dropdown-item-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!