将视图绑定到Flutter中的对象列表

pgvzfuti  于 2023-05-08  发布在  Flutter
关注(0)|答案(1)|浏览(108)

我有一个Student的列表,我需要为每个学生在页面上显示。可以使用底部提供的下一个和上一个按钮来迭代列表。

class Student {
  String name;
  String contact;
  String address;
}

List<Student> students = []; // Assuming I have some Student objects here

我无法确定我应该如何继续为我的需求构建UI并将列表绑定到同一个。

ahy6op9u

ahy6op9u1#

class Student {
  final String name;
  final int age;

  Student({required this.name, required this.age});
}

class StudentListPage extends StatefulWidget {
  final List<Student> students;

  StudentListPage({required this.students});

  @override
  _StudentListPageState createState() => _StudentListPageState();
}

class _StudentListPageState extends State<StudentListPage> {
  int _currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Student List'),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: widget.students.length,
              itemBuilder: (BuildContext context, int index) {
                final student = widget.students[index];
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('Name: ${student.name}'),
                      Text('Age: ${student.age}'),
                    ],
                  ),
                );
              },
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: _currentIndex == 0
                    ? null
                    : () {
                        setState(() {
                          _currentIndex--;
                        });
                      },
                child: Text('Previous'),
              ),
              SizedBox(width: 16.0),
              ElevatedButton(
                onPressed: _currentIndex == widget.students.length - 1
                    ? null
                    : () {
                        setState(() {
                          _currentIndex++;
                        });
                      },
                child: Text('Next'),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

相关问题