Я пытаюсь создать простой проект флаттера для обучения. Мне нужно написать выбранное имя студента на экране, но setState не работает. Он меняет переменную, но не отображает на экране. -Photo- Вот что я хочу. Например, когда я нажимаю на Name3 LastName3, я хочу, чтобы внизу было написано «Name3 LastName3».

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("Student Exam Result System"),
      ),
      body: bodyBuilder(context),
    );
  }
bodyBuilder(BuildContext context) {
    String ChoosedStudent = "";
    StudentManager student1 = new StudentManager("Name1", "LastName1", 22,
        "https://uifaces.co/our-content/donated/hvaUVob5.jpg");
    StudentManager student2 = new StudentManager("Name2", "LastName2", 70,
        "https://uifaces.co/our-content/donated/eqUZLcBO.jpg");
    StudentManager student3 = new StudentManager("Name3", "LastName3", 55,
        "https://uifaces.co/our-content/donated/-oe25tWA.png");
    StudentManager student4 = new StudentManager("Name4", "LastName4", 99,
        "https://images.generated.photos/ukvWCGJJF8xoZ_rvVSFDLnQ-WDkGw2WsZ53uPPm63M8/rs:fit:512:512/Z3M6Ly9nZW5lcmF0/ZWQtcGhvdG9zLzA3/OTI0MTAuanBn.jpg");
    StudentManager student5 = new StudentManager(
        "Name5", "LastName5", 45, "https://thispersondoesnotexist.com/image");
    List<StudentManager> StudentList = [
      student1,
      student2,
      student3,
      student4,
      student5
    ];

    return Column(
      children: [
        Expanded(
            child: ListView.builder(
                itemCount: StudentList.length,
                itemBuilder: (BuildContext context, int index) {
                  if (StudentList[index].Grade >= 50) {
                    StudentList[index].IsPassed = true;
                  } else if (StudentList[index].Grade < 50) {
                    StudentList[index].IsPassed = false;
                  }
                  return ListTile(
                    leading: CircleAvatar(
                      backgroundImage:
                          NetworkImage(StudentList[index].PhotoURL),
                    ),
                    title: Text(StudentList[index].Name +
                        " " +
                        StudentList[index].Surname),
                    subtitle: Text(
                        "${StudentList[index].Name} named students grade is "
                        "${StudentList[index].Grade}, ${StudentList[index].AlphebaticalGrade}"),
                    isThreeLine: true,
                    trailing: buildStatusIcon(StudentList[index].IsPassed),
                    onTap: () {
                      setState(() {
                        ChoosedStudent = StudentList[index].Name +
                            " " +
                            StudentList[index].Surname;
                      });
                    },
                  );
                })),
        Text("Student: " + ChoosedStudent),
        Center(),
      ],
    );
  }
}

Widget buildStatusIcon(bool IsPassed) {
  if (IsPassed == true) {
    return Icon(Icons.done);
  } else if (IsPassed == false) {
    return Icon(Icons.warning);
  } else {
    return Icon(Icons.error);
  }
}

Не знаю, нужно ли, но вот студенческий класс:

class StudentManager{
  String Name;
  String Surname;
  int Grade;
  String AlphebaticalGrade;
  bool IsPassed;
  String PhotoURL;
  StudentManager(String Name, String Surname, int Grade, String PhotoURL){
    this.Grade = Grade;
    this.Surname = Surname;
    this.Name=Name;
    this.PhotoURL = PhotoURL;
    if (Grade >= 90 && Grade <= 100) {
      AlphebaticalGrade = "A+";
    } else if (Grade >= 80 && Grade <= 90) {
      AlphebaticalGrade = "A";
    } else if (Grade >= 70 && Grade <= 80) {
      AlphebaticalGrade = "B+";
    } else if (Grade >= 60 && Grade <= 70) {
      AlphebaticalGrade = "B";
    } else if (Grade >= 50 && Grade <= 60) {
      AlphebaticalGrade = "D+";
    } else if (Grade >= 40 && Grade <= 50) {
      AlphebaticalGrade = "D";
    } else if (Grade <= 39 && Grade <= 40) {
      AlphebaticalGrade = "F";
    } else {
      AlphebaticalGrade =
      "The grade is unknown please contact with your teacher";
    }

  }


}

(Я знаю, что на нем нет нот C или C +: D)

0
Meany0 16 Янв 2021 в 19:23

2 ответа

Лучший ответ
class _MyAppState extends State<MyApp> {
  String ChoosedStudent = "";
  // ↑ As a field, will not be reset during build method call

  // ↓ build method called on setState. Any "state" inside build will be lost upon rebuild
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Student Exam Result System"),
      ),
      body: bodyBuilder(context),
    );
  }
bodyBuilder(BuildContext context) {
    // ↓ MOVE THIS UP AS A FIELD
    // String ChoosedStudent = "";
0
Baker 16 Янв 2021 в 18:38

Вы должны определить String ChoosedStudent = ""; как глобальную переменную.
Пожалуйста, попробуйте поместить его прямо под class _MyAppState extends State<MyApp> {

0
beerstorm 16 Янв 2021 в 16:37