I just started learning Dart and Flutter.I have data in a listview widget in my main.dart file. I'm adding one more data to it and I have a StudentAdd class. Here is my code but the data on my page is not updated automatically without clicking the screen.When I run the code my new data don't show in listview. What is my mistake?
Advance thanks for your answer.
import 'package:flutter/material.dart';
import 'package:temel_widget/models/student.dart';
import 'package:temel_widget/validation/student_validator.dart';
class StudentAdd extends StatefulWidget {
List<Student> students;
StudentAdd(List<Student> students) {
this.students = students;
}
@override
State<StatefulWidget> createState() {
return _StudentAddState(students);
}
}
class _StudentAddState extends State with StudentValidationMixin {
List<Student> students;
var student = Student.withoutInfo();
var formKey = GlobalKey<
FormState>();
_StudentAddState(List<Student> students) {
this.students = students;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Yeni Öğrenci Ekle"),
),
body: Container(
margin: EdgeInsets.all(20.0),
child: Form(
key: formKey,
child: Column(
children: <Widget>[
buildFirstNameField(),
buildLastNameField(),
buildGradeField(),
buildSubmitButton(),
],
)),
));
}
Widget buildFirstNameField() {
return TextFormField(
decoration:
InputDecoration(labelText: "Öğrenci Adı:", hintText: "isim girin"),
validator: validateFirstName,
onSaved: (String value) {
student.firstName = value;
},
);
}
Widget buildLastNameField() {
return TextFormField(
decoration:
InputDecoration(labelText: "Öğrenci Soyadı:", hintText: "soyisim girin"),
validator: validateLastName,
onSaved: (String value) {
student.lastName = value;
},
);
}
Widget buildGradeField() {
return TextFormField(
decoration: InputDecoration(labelText: "Aldığı Not:", hintText: "0"),
validator: validateGrade,
onSaved: (String value) {
student.grade = int.parse(value);
},
);
}
Widget buildSubmitButton() {
return RaisedButton(
child: Text("KAYDET"),
onPressed: () {
if (formKey.currentState.validate()) {
formKey.currentState.save();
saveStudent();
students.add(student);
Navigator.pop(context);
}
},
);
}
void saveStudent() {
print(student.firstName);
print(student.lastName);
print(student.grade);
}
}
Yes this is because the code to add the data is not written under
setState((){})
block. Try again by doing as follows: