将 MySQL 数据库中的数据填充到 DropDown 中

Populating data from MySQL Database to DropDown in flutter

我有来自数据库的两个不同列表中的数据,这些数据是使用 POST 请求获取的。我想将此数据弹出到两个不同的 DropdownButton。屏幕打开时获取数据。我在特定屏幕的 initstate() 中调用了该方法。 以下是我获取数据和创建列表的方式:

void fetchData() {
  AppUtils.getStringFromPref("teacher_id").then(
    (teacher_id) async {
      final data = await http
          .post(AppUtils.teacherHomeLink, body: {"teacher_id": teacher_id});
      var responseBody = data.body;
      print(responseBody);
      final parsed = json.decode(data.body).cast<Map<String, dynamic>>();

      List<TeacherHomeData> parentSigninList = parsed
          .map<TeacherHomeData>((json) => TeacherHomeData.fromJson(json))
          .toList();

      for (int i = 0; i < parentSigninList.length; i++) {
        courseNameList.add(parentSigninList[i].course_name);
        batchNameList.add(parentSigninList[i].batch_name);
      }
    },
  );
}

创建 DropDownButton 的方式如下:

DropdownButton(
  value: courseName,
  items: courseNameList.map((location) {
    return DropdownMenuItem(
      child: new Text(location),
      value: location,
    );
  }).toList(),
  onChanged: (newValue) {
    setState(() {
      courseName = newValue;
    });
  },
),

问题
当屏幕加载时,它会立即创建一个空的 DropDownButton,因为列表最初是空的。我希望 DropDownButton 等到列表从数据库中成功获取。作为 Flutter 的初学者,我找到了正确的方法。

最好的方法是使用 Future 函数和 FutureBuilder 来获取异步数据并在小部件的构建方法中使用它。将您的函数转换为 Future;

Future<List> fetchData() async {
  var teacher_id = await AppUtils.getStringFromPref("teacher_id");
  final data = await http
      .post(AppUtils.teacherHomeLink, body: {"teacher_id": teacher_id});
  var responseBody = data.body;
  print(responseBody);
  final parsed = json.decode(data.body).cast<Map<String, dynamic>>();

  List<TeacherHomeData> parentSigninList = parsed
      .map<TeacherHomeData>((json) => TeacherHomeData.fromJson(json))
      .toList();

  for (int i = 0; i < parentSigninList.length; i++) {
    courseNameList.add(parentSigninList[i].course_name);
    batchNameList.add(parentSigninList[i].batch_name);
  }
  return courseNameList;
}

并在从服务器获取数据后使用 FutureBuilder 构建您的小部件;

FutureBuilder<List>(
  future: fetchData(),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return DropdownButton(
        value: courseName,
        items: snapshot.data.map((location) {
          return DropdownMenuItem(
            child: new Text(location),
            value: location,
          );
        }).toList(),
        onChanged: (newValue) {
          setState(() {
            courseName = newValue;
          });
        },
      );
    }
    return Center(child: CircularProgressIndicator());
  },
),