#flutter #validation #dart #null
Вопрос:
Ошибка:
The following _TypeError was thrown while routing a pointer event:
type 'Null' is not a subtype of type 'String' of 'function result'
When the exception was thrown, this was the stack:
#0 _Location.file (package:flutter/src/widgets/widget_inspector.dart)
#1 _Location.toJsonMap (package:flutter/src/widgets/widget_inspector.dart:2844:15)
#2 _Location.toJsonMap.<anonymous closure> (package:flutter/src/widgets/widget_inspector.dart:2853:42)
#3 MappedListIterable.elementAt (dart:_internal/iterable.dart:412:31)
#4 ListIterator.moveNext (dart:_internal/iterable.dart:341:26)
...
Вот мой код:
import 'package:flutter/material.dart';
class Signup3 extends StatefulWidget {
const Signup3({Key? key}) : super(key: key);
@override
_Signup3State createState() => _Signup3State();
}
class _Signup3State extends State<Signup3> {
GlobalKey<FormState> formstate = new GlobalKey<FormState>();
send() {
setState(() {
var formdata = formstate.currentState;
var fdcurrent = formdata!.validate();
if (fdcurrent == null) {
print("sendon");
} else {
print("sendoff");
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("signup"),
),
body: Form(
child: Column(
children: [
TextFormField(
validator: (text) {
String? f = " ";
f = text;
int counter = f!.length;
if (counter < 3) {
return "too small";
} else {
return "valid";
}
},
),
ElevatedButton(
onPressed: send,
child: Text("submit"),
),
],
),
),
);
}
}
Комментарии:
1. Происходит ли это только тогда, когда вы очищаете поле текстовой формы и нажимаете кнопку отправить?
2. Это полный маршрут следования?
Ответ №1:
Вы должны добавить key: formstate
в форму виджет
body: Form(
key: formstate,// <-- add this line
child: Column(
children: [ ...