我是 flutter 的新手,在這個簡單的代碼中,我收到了一個錯誤
用于空值的 NULL 檢查運算子
我嘗試了此處提供的所有解決方案(我在終端中運行所有命令,例如 flutter upgrade 等),但仍然遇到相同的錯誤。
import 'package:flutter/material.dart';
Future<void> main() async{
WidgetsFlutterBinding.ensureInitialized();
runApp(MaterialApp(
home: Home(),
));
}
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
final _key =GlobalKey<FormState>();
final textformfield=TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: Column(
children: [
SizedBox(height: 300,),
TextFormField(
controller: textformfield,
key: _key,
validator: (value){
if(value!.isEmpty){
return "Please enter your email";
}
else return null;
},
),
FlatButton(
onPressed: (){
if(_key.currentState!.validate()){
print("validate");
}
else print('NUll');
},
child: Text('Validate')
),
],
),
),
),
);
}
}
uj5u.com熱心網友回復:
試試下面的代碼希望對你有幫助。在里面添加小部件Form()并使用 TextButton 而不是 FlatButton 因為 FlatButton 已被 flutter 棄用
請參閱此處的表單驗證
Form(
key: _key,
child: Column(
children: [
SizedBox(
height: 300,
),
TextFormField(
controller: textformfield,
validator: (value) {
if (value!.isEmpty) {
return "Please enter your email";
} else
return null;
},
),
TextButton(
onPressed: () {
if (_key.currentState!.validate()) {
print("validate");
} else
print('NUll');
},
child: Text('Validate')),
],
),
),
uj5u.com熱心網友回復:
首先,您需要有一個 Form Widget 并將 TextFormFields 放入其中。https://docs.flutter.dev/cookbook/forms/validation
return Form(
key: _key,
child: Column(
children: <Widget>[
// Add TextFormFields and ElevatedButton here.
],
),
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/370358.html
