Code used in the video:
import 'package:flutter/material.dart';
import 'package:lessons/widget_creator.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _schoolIdController = TextEditingController();
TextEditingController _nameController = TextEditingController();
TextEditingController _courseController = TextEditingController();
List<Map<String, dynamic>> _studentList = [];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
createHeaders("Flutter University hehehe", "Working with Maps"),
vSpacer(10.0),
createTextField(
controller: _schoolIdController, labelText: "School ID"),
vSpacer(10.0),
createTextField(controller: _nameController, labelText: "Name"),
vSpacer(10.0),
createTextField(
controller: _courseController, labelText: "Course"),
vSpacer(10.0),
ElevatedButton(
onPressed: () {
saveRecord(_schoolIdController.text, _nameController.text,
_courseController.text);
},
style: ElevatedButton.styleFrom(backgroundColor: Colors.green),
child: const Text(
"Save",
style: TextStyle(
color: Colors.white,
),
),
),
//listview
Expanded(
child: createListview(),
),
],
),
),
),
);
}
void saveRecord(String schoolId, String name, String course) {
// declare the map
Map<String, dynamic> _studentMap = {
"schoolId": schoolId,
"name": name,
"course": course
};
// assign values to the map
// _studentMap["schoolId"] = schoolId;
// _studentMap["name"] = name;
// _studentMap["course"] = course;
// add the map to the list
setState(() {
_studentList.add(_studentMap);
_studentList.sort((a, b) => a["name"].compareTo(b["name"]));
});
// print the list
// print(_studentList);
// print(_studentList[0]["name"]);
}
Widget createListview() {
return ListView.builder(
itemCount: _studentList.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(_studentList[index]["name"]),
subtitle: Text(_studentList[index]["course"]),
trailing: IconButton(
onPressed: () {
displaySelected(index);
},
icon: const Icon(Icons.arrow_right)),
),
);
},
);
}
void displaySelected(int index) {
String name = _studentList[index]["name"];
String course = _studentList[index]["course"];
String id = _studentList[index]["schoolId"];
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("You selected $name of $course with ID $id"),
),
);
}
}
No comments:
Post a Comment