0

重现步骤

  1. 这是 dartpad 链接转到它。
  2. 在字段中输入任何值来计算答案。
  3. 在任何字段的开头添加 0

预期结果:验证器应返回 0.xyz

实际结果:验证器返回 0xyz

找到解决方法:使用 onSaved 解决了这个问题

谁能告诉我为什么会这样或者它是颤振中的错误然后我将在颤振回购中出现一个新问题

问题

我正在打印来自验证器的值,并在 onChanged 中将字符串值解析为 int。

4

2 回答 2

1


输入时编辑23然后惰性0.,此行amount = int.parse(val); 执行并停止然后单击计算按钮,所以数量是23value'sruntimeTypeString 023

TextFormField(
  keyboardType: TextInputType.number,
  validator: (value) {
    print("amount $amount");
    print(" ${value.runtimeType}");
    print("validator amount value $value ");
    if (value.isEmpty) {
      return "Enter some amount";
    } else if (double.parse(value).toInt() <= 0) {
      return "Amount should be greater than 0";
    }
    return null;
  },
  onChanged: (val){
    print("val1 $val");
    amount = int.parse(val);
    print("amount $amount");
  }

您可以在下面复制粘贴运行完整代码
原因为什么validator不返回0.xyz
因为onChanged之前执行validator
所以validator接收截断值int.parse(value)
如果您删除amount = int.parse(value);验证器将获得正确的值但此条件if (int.parse(value) <= 0) 将获得Invalid radix-10 number
您需要更改为if (double.parse(value).toInt() <= 0)

工作演示

在此处输入图像描述

完整代码

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.purple,
        buttonTheme: ButtonThemeData(
          buttonColor: Colors.purple.shade400,
        ),
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: BillSpitApp(),
    );
  }
}

class BillSpitApp extends StatefulWidget {
  BillSpitApp({Key key}) : super(key: key);

  @override
  _BillSpitAppState createState() => _BillSpitAppState();
}

class _BillSpitAppState extends State<BillSpitApp> {
  int amount;
  int numOfPersons;
  double splitAmount;

  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Bill split app"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(15.0),
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                splitAmount == null
                    ? "Fill the details and click on calculate to get your bill split"
                    : "Bill split is ${splitAmount.toStringAsFixed(2)}",
                style: TextStyle(
                  fontSize: 25,
                ),
                textAlign: TextAlign.center,
              ),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 15.0),
                child: TextFormField(
                  keyboardType: TextInputType.number,
                  validator: (value) {
                    print("validator amount value $value");
                    if (value.isEmpty) {
                      return "Enter some amount";
                    } else if (double.parse(value).toInt() <= 0) {
                      return "Amount should be greater than 0";
                    }
                    return null;
                  },
                  onSaved: (value) {
                    print("onSaved amount value $value");
                    amount = int.parse(value);
                    //int.parse(value);
                  },
                  decoration: InputDecoration(
                    labelText: "Amount",
                    hintText: "1000",
                    border: OutlineInputBorder(),
                  ),
                ),
              ),
              TextFormField(
                validator: (value) {
                  print("person value $value");
                  if (value.isEmpty) {
                    return "Enter number of persons";
                  } else if (double.parse(value).toInt() <= 0) {
                    return "Number should be greater than 0";
                  }
                  return null;
                },
                onSaved: (value) {
                  print("onsave numOfPersons $value");
                  numOfPersons = int.parse(value);
                },
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  labelText: "Number of persons",
                  hintText: "5",
                  border: OutlineInputBorder(),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 15.0),
                child: RaisedButton(
                  child: Text(
                    "Calculate",
                    style: TextStyle(color: Colors.white),
                  ),
                  onPressed: () {
                    if (_formKey.currentState.validate()) {
                      _formKey.currentState.save();
                      print("calculate $amount");
                      print("calculate $numOfPersons");
                      setState(() {
                        splitAmount = amount / numOfPersons;
                      });
                    }
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
于 2020-09-16T06:22:54.697 回答
1

这不是颤振错误,但是当您将数量作为整数时,任何值都以 0 开头,颤振将其视为 0。

if (value.isEmpty) {
   return "Enter some amount";
} else if (double.parse(value) <= 0) {
   return "Amount should be greater than 0";
}
return null;

onChanged: (value) {
   amount = double.parse(value);
},
于 2020-09-16T06:47:33.187 回答