Home > front end >  How can ı change a list from main dart in another page
How can ı change a list from main dart in another page

Time:09-11

I want the user to go to the add user screen by clicking the add button that I added to the main page and fill out the form on this screen. But this is not the most important thing. I want the information in the form filled in the add page to be added as a new element to my list that I created manually on the main page and a list to be drawn again on the screen with the listvievbuilder structure, but I cannot access the . When the list and the form are on the same page, I can add a new user as I want, so my problem is how can I access the user list I created on the main page (main.dart) and all its functions on another screen, what should I do to access it(the form ı made it. not screen)?

//my code(main.dart)

import 'package:flutter/material.dart';
import 'package:flutter_application_1/models/Student.dart';
import 'package:flutter_application_1/screens/student_AddForm.dart';

void main() {
  runApp(const MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Student> students1 = [
    Student("İlknur", "Kaya", 100),
    Student("Taner", "Genco", 80),
  ];
  var selectedStudent = Student.withOutInfo();

  late Student student = student;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("ANASAYFA"),
          centerTitle: true,
        ),
        body: Column(
          children: [
            Expanded(
              child: ListView.builder(
                  itemCount: students1.length,
                  itemBuilder: (BuildContext context, int index) {
                    return ListTile(
                      leading: const CircleAvatar(
                        backgroundColor: Colors.redAccent,
                      ),
                      title: Text(
                          "${students1[index].firstName} ${students1[index].lastName}"),
                      subtitle: Text(students1[index].grade.toString()  
                          students1[index].getStatus()),
                      trailing: buildStatusIcon(students1[index].grade),
                      onTap: () {
                        setState(() {
                          selectedStudent = students1[index];
                        });
                      },
                    );
                  }),
            ),
            Text(
                "Seçili öğrenci : ${selectedStudent.firstName} ${selectedStudent.lastName}"),
            Row(
              children: [
                Flexible(
                  fit: FlexFit.tight,
                  flex: 1,
                  child: ElevatedButton(
                      onPressed: () {
                        setState(() {
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => StudentAddForm(),
                              ));
                        });
                      },
                      child: const Text("EKLE")),
                ),
                Flexible(
                  fit: FlexFit.tight,
                  flex: 1,
                  child: ElevatedButton(
                      onPressed: () {}, child: const Text("GÜNCELLE")),
                ),
                Flexible(
                  fit: FlexFit.tight,
                  flex: 1,
                  child: ElevatedButton(
                      onPressed: () {
                        setState(() {
                          students1.remove(selectedStudent);
                        });
                      },
                      child: const Text("SİL")),
                ),
              ],
            )
          ],
        ));
  }

  buildStatusIcon(int grade) {
    if (grade >= 50) {
      return const Icon(Icons.done);
    } else if (grade >= 40) {
      return const Icon(Icons.album);
    } else {
      return const Icon(Icons.clear);
    }
  }
}

//my code(Scrrens(student.dart))

class Student {
  String? firstName;
  String? lastName;
  late int grade;
  late int Id;
  Student(this.firstName, this.lastName, this.grade);
  Student.withOutInfo();
  Student.withId(this.Id, this.firstName, this.lastName, this.grade);
  String getStatus() {
    if (grade >= 50) {
      return "Geçti";
    } else if (grade >= 40) {
      return "Bütünlemeye Kaldı";
    } else {
      return "Kaldı";
    }
  }
}

//my code(studentAddForm.dart)

// ignore_for_file: public_member_api_docs, sort_constructors_first, no_logic_in_create_state
// ignore_for_file: file_names, must_be_immutable

import 'package:flutter/material.dart';
import 'package:flutter_application_1/main.dart';
import 'package:flutter_application_1/models/Student.dart';

class StudentAddForm extends StatefulWidget {
  @override
  State<StudentAddForm> createState() => _StudentAddFormState();
}

class _StudentAddFormState extends State<StudentAddForm> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  var student = Student("-", "-", 0);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("EKLEME SAYFASI"),
          leading: IconButton(
            icon: const Icon(Icons.home),
            onPressed: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const MyApp(),
                  ));
            },
          ),
          centerTitle: true,
        ),
        body: Form(
            key: _formKey,
            child: Column(
              children: [
                TextFormField(
                  decoration: const InputDecoration(
                      labelText: "Adınızı Girin",
                      counterText: "Örneğin Ali Erdem",
                      border: OutlineInputBorder()),
                  onSaved: (newValue) {
                    student.firstName = newValue;
                  },
                  validator: (value) {
                    if (value!.isEmpty || value.length < 3) {
                      return "Adınız en az üç karakter olmalıdır";
                    } else if (value.contains("0") ||
                        value.contains("1") ||
                        value.contains("2") ||
                        value.contains("3") ||
                        value.contains("4") ||
                        value.contains("5") ||
                        value.contains("6") ||
                        value.contains("7") ||
                        value.contains("8") ||
                        value.contains("9")) {
                      return "Adınız sayı içeremez";
                    } else {
                      return null;
                    }
                  },
                ),
                TextFormField(
                  decoration: const InputDecoration(
                      labelText: "Soyadınızı Girin",
                      counterText: "Örneğin Toraman",
                      border: OutlineInputBorder()),
                  onSaved: (newValue) {
                    student.lastName = newValue;
                  },
                  validator: (value) {
                    if (value!.isEmpty || value.length < 3) {
                      return "Adınız en az üç karakter olmalıdır";
                    } else if (value.contains("0") ||
                        value.contains("1") ||
                        value.contains("2") ||
                        value.contains("3") ||
                        value.contains("4") ||
                        value.contains("5") ||
                        value.contains("6") ||
                        value.contains("7") ||
                        value.contains("8") ||
                        value.contains("9")) {
                      return "Adınız sayı içeremez";
                    } else {
                      return null;
                    }
                  },
                ),
                TextFormField(
                  decoration: const InputDecoration(
                      labelText: "Sınav Notunuzu Giriniz",
                      counterText: "Örneğin 55",
                      border: OutlineInputBorder()),
                  keyboardType: const TextInputType.numberWithOptions(),
                  onSaved: (newValue) {
                    student.grade = int.parse(newValue!);
                  },
                  validator: (value) {
                    if (value!.isEmpty) {
                      return "Boş Bırakılamaz";
                    } else if (int.parse(value) < 0 || int.parse(value) > 100) {
                      return " 0 - 100 aralığında olmalıdır";
                    } else {
                      return null;
                    }
                  },
                ),
                IconButton(
                    onPressed: () {
                      if (_formKey.currentState!.validate()) {
                        _formKey.currentState!.save();
                        debugPrint(student.firstName);
                      }
                    },
                    icon: const Icon(Icons.done))
              ],
            )),
      ),
    );
  }
}

CodePudding user response:

you can pass a callback from your MyApp and call it when pressing the save button.

CodePudding user response:

put list outside form class

like:

void main(){
 print(students1[0]);
 students1[0].remove;
}
 List<Student> students1 = [
  Student("İlknur", "Kaya", 100),
  Student("Taner", "Genco", 80),
  ];
class name{}
  • Related