How to take integer input from user in dart - flutter

i am new in dart and just want to know how to take integer input from user in dart with null safety. i found out a way to take number input from dart which is:
String? chossenNumber = stdin. readLineSync();
if(chossenNumber !=null)
{
int number = int.parse(chossenNumber);
}
but i am unable to use number variable outside of the scope. Please tell me a way to solve this issue.

You can define the variable at the top of the class and initialize it here so you will be able to use it everywhere in the class

The solution of it very simple just take input of number as String i.e
String? chossenNumber = stdin. readLineSync();
and when you want to use this variable parse it to the 'int' i.e
if(int.parse(chossenNumber) <100)
{
print("Your Statement");
}

Related

Flutter null-safety conditionals in object methods

I'm just working through this whole null-safety mode with my Flutter project and unsure what the difference is with ? and ! in calls to object methods.
For example, the hint was to add a ! conditional. Here's an example I have right now, and I'm unsure if this should be a ? or a ! at the findNbr!.replaceAll().
Future checkItem({String? findNbr}) async {
int? x = int.tryParse(findNbr!.replaceAll('-', ''));
...
Does this mean replaceAll() will not run if findNbr is null?
Or should it be a ? instead? findNbr?.replaceAll()
EDIT: I just noticed I cannot use findNbr?, it's telling String? can't be assigned parameter String.
Or does it mean I say it's not null and run it anyway?
For your information, I have not come close to running my app yet so I have no idea if it even works. But I figure I better know what it's doing before get too much more done. I'm still in the process of converting everything and there's 75-100 dart files. I'm not sure I get the point of it all to be honest, because I just add ? to everything, so its all nullable anyway.
Future checkItem({String? findNbr}) async {
int? x = int.tryParse(findNbr!.replaceAll('-', ''));
...
Does this mean replaceAll() will not run if findNbr is null?
Correct. If findNbr is null, then findNbr! will throw a runtime exception. That would be bad, especially since checkItem's function signature advertises that findNbr is allowed to be null, and therefore it would violate callers' expectations.
Or should it be a ? instead? findNbr?.replaceAll()
EDIT: I just noticed I cannot use findNbr?, it's telling String? can't be assigned parameter String.
You can't use findNbr?.replaceAll(...) because if findNbr is null, then it would be invoking int.tryParse(null), but int.tryParse is not allowed to take a null argument.
What you need to do is one of:
Make findNbr no longer optional:
Future checkItem({required String findNbr}) async {
int? x = int.tryParse(findNbr.replaceAll('-', ''));
...
Allow findNbr to be optional but have a non-null default value:
Future checkItem({String findNbr = ''}) async {
int? x = int.tryParse(findNbr.replaceAll('-', ''));
...
Allow findNbr to be optional but explicitly decide what to do if it is null. For example:
Future checkItem({String? findNbr}) async {
int? x = findNbr == null ? null : int.tryParse(findNbr.replaceAll('-', ''));
...
I'm not sure I get the point of it all to be honest, because I just add ? to everything, so its all nullable anyway.
If you blindly add ? to all types and add ! to all variables, then yes, null-safety would be pointless: doing that would give you the same behavior as Dart before null-safety.
The point of null-safety is to prevent things that shouldn't be null from ever being null. You could have written such code before, but without null-safety, that meant performing runtime null checks (e.g. assert(x != null);, if (x != null) { ... }, or relying on a null-pointer-exception to crash the program if null was used where it wasn't expected). Null-safety means that such checks now can be done at build-time by static analysis, which means that errors can be caught earlier and more completely. Furthermore, whereas previously functions needed to explicitly document whether arguments and return values were allowed to be null (and inadequate or incorrect documentation could be a source of errors), now they're self-documenting in that regard. It's just like using int foo(String s) versus dynamic foo(dynamic s); using strong types catches errors earlier and better describes the function's contract.
I recommend reading Understanding Null Safety if you haven't already done so.
I would like to advice you to use the ! operator, also the called bang operator, as little as possible. You should only use this operator when the dart analyser is wrong and you know for 100% that the value will never be null.
Below is an example of where the dart analyser would be wrong and you should use the bang operator.
// We have a class dog with a nullable name.
class Dog {
String? name;
Dog({this.name});
}
void main() {
// We create a dog without a name.
final dog = Dog();
// We assign the dog a name.
dog.name = 'George';
// The dart analyser will show an error because it can't know if the
// name of the object is not null.
//
// Will throw: `A value of type 'String?' can't be assigned to a
// variable of type 'String'`.
String myDogsName = dog.name;
// To avoid this, you should use the bang operator because you `know` it
// is not null.
String myDogsName = dog.name!;
}
The ? operator simply tells Dart that the value can be null. So every time you want to place a ? operator, ask yourself, can this value ever be null?
The null safety features in Dart are mainly created for helping the developer remember when a value can be null. Dart will now simply tell you when you made a variable nullable in order to force null checks or default values for example.

The argument type 'String?' can't be assigned to the parameter type 'String'

when I upgrade my flutter to 2.0.1, shows this error:
The argument type 'String?' can't be assigned to the parameter type 'String'.
this is my code:
enum SubStatus {
SUB,
UNSUB,
}
extension ResponseStatusExtension on SubStatus{
static const statusCodes = {
SubStatus.SUB: "sub",
SubStatus.UNSUB: "unsub",
};
String? get statusCode => statusCodes[this];
}
This is how to use it:
String url = "/post/sub/source/" + subStatus.statusCode + "/" + channelId;
this is the error UI:
what should I do to fix it? I tried to return String but in the enum code tell me should return String?:
what should I do?
Change the return type of statusCode to String and provide a default value.
String get statusCode => statusCodes[this] ?? '';
When accessing a map, there is a chance that you will get a null return value if the key does not exist in the map. Simply providing a default value will allow this code to compile. That default value should never be used unless you add something to the enum without adding a value to the map as well.
Edit:
After the comment from #Christopher Moore, I realized my mistake. So, I am going to directly use his solution over here as it is the correct one.
This is because of the new null-safety feature of Dart.
You will need to make the following change in the code and it will work:
String get statusCode => statusCodes[this] ?? '';
With new null-safety rules, the following data-type? x, the data type is followed by a question mark, means that the value x can be null. However, without the '?', it means that data-type x, it cannot be null.
So, basically String and String? are two different data types. That is why you get the error.
You can learn more here.
restart analysis server
add !
like this
subStatus.statusCode!

Dart: How to force string interpolation on a variable

I have a variable that contains a string with interpolated variables. In the code below, that variable is template. When I pass this variable to generateString function, I want to apply string interpolation on it because the values which interpolated variables require are available in generateString function only.
void main() {
String template = '<p>\${name}</p>';
var res = generateString(template);
}
generateString(template) {
var name = 'abc';
print(template);
return template;
}
The problem is when I am printing and returning template inside generateString fn, I am getting <p>${name}</p> instead of <p>abc</p>. Is there a way to explicitly tell the dart to so string interpolation?
I am new to Dart. I don't know if it is even possible to achieve or not. Please suggest how do I do this.
Edit: Based on the inputs from other users, I would like to make a clarification about the scenario presented. The value of template variable is not a string literal. I get that from UI as a user input. I have shown it here as a string literal for code simplicity. Also, please consider that name and template are not in the same scope in my scenario.
The other answers so far are wrong.
String interpolation (looking for $, etc) happens only while compiling from the source code to the value in memory. If that string in turn also has a $, it's no longer special.
It's not possible to trigger interpolation past the original compilation step. You can write a templating system that would look for something like {{name}} in the value, and replace it with the current value of name.
If you have the template and the variable in the same scope, it works as expected.
// evaluate variable inside ${}
var sport = 'basketball';
String template = 'I like <p>${sport}</p>';
print(template);
I didn't fully understand your question maybe this will help
void main() {
print(generateString('abc')); //<p>abc</p>
}
generateString(String template) {
return r"<p>" "$template" r"</p>";
}
Walter White here.
You must define the variable name as global var, so it can "cook" the string for you

How to use optional in Dart for null safety

I found this package that implements Optional for Dart: https://pub.dev/packages/optional/example
On the examples, it does things like this:
void filterExample() {
final hello = Optional.of('hello');
final world = Optional.of('world');
final name = Optional.of('harry');
for (var o in [hello, world, name]) {
final filtered = o.filter((v) => v.startsWith('h'));
print(filtered.isPresent);
} // prints "true", "false", "true"
}
But how do I force a variable to be Optional of some type? I wanted to have Optional<String>, Optional<int>, etc, but I'm forced to give a value in the beginning.
The closest I can think is
final anEmpty = Optional.ofNullable(null);
which is already in the example, but what is a Nullable? If I do like this, I cannot constraint the value to be a String or int, it can be changed to anything. I want to stick to strong typing while using Optional.
If this is not possible with this library, then how can I make my own simple Optional type that supports templates so I can have Optional<String>, Optional<int>, etc?
The behavior you are looking for (doing something if null and something else otherwise) can be achieved using the ?? operator.
This is basically a null check which equals the left hand if not null and right hand if null. Example: doSomething(myString ?? "Default value of my string");
Does this answer your question? Sorry, I haven't used that package and don't see a need to.

Should I always use "this" in Dart?

Is it a good practice to use always 'this' in a method.
Even if there is no usage of the same variable name as input to this method.
String getStory(number) {
return this.storyData[number];
}
By doing this there won't have any conflicts with any input variable name (never).
Thank you in advance for your feedback.
Generally this. is only supposed to be used when there is ambiguity about what variable is being used.
class Test{
final int x;
Test(this.x);
}