无法在 flutter 的验证器中获得正确的值

Cannot get proper value in validator in flutter

重现步骤

  1. Here is the dartpad link去吧
  2. 在字段中输入任何值计算答案。
  3. 在任何字段的开头添加 0.

预期结果: 验证者应该 return 0.xyz

实际结果:验证者returns 0xyz

解决方法发现: 使用 onSaved 解决了这个问题

任何人都可以告诉我为什么会发生这种情况或者它是 flutter 中的错误然后我将在 flutter repo 中发布一个新问题

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

编辑
当输入 23 然后 inert 0. 时,这一行 amount = int.parse(val); 执行并停止然后点击计算按钮,所以数量是 23valueruntimeTypeString 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不是return0.xyz
因为 onChangedvalidator 之前执行
所以 validator 通过 int.parse(value)
接收 t运行 的值 如果您删除 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;
                      });
                    }
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

这不是 flutter 的 bug,但是当你将 amount 取为整数时,任何以 0 开头的值,flutter 都会将其视为 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);
},