API数据未显示在Flutter下拉菜单中

6kkfgxo0  于 2023-02-05  发布在  Flutter
关注(0)|答案(3)|浏览(143)

我试图显示数据列表API下拉菜单,但结果不存在,我必须修复。我试图更改或更新用户数据,并在列表中包括用户可以选择国家,宗教等形式的一些数据。其中我如何使它。
获取API

Future<UserBiodata> getBiodata() async {
    String url = Constant.baseURL;
    String token = await UtilSharedPreferences.getToken();
    final response = await http.get(
      Uri.parse(
        '$url/auth/mhs_siakad/biodata',
      ),
      headers: {
        'Authorization': 'Bearer $token',
      },
    );

    print(response.statusCode);
    print(response.body);
    if (response.statusCode == 200) {
      return UserBiodata.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Token Expired!');
    }
  }

在窗口小部件中显示

String? _mySelection;

  List<Agama> agama = [];

  @override
  void initState() {
    super.initState();
    BiodataProvider().getBiodata();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(kToolbarHeight),
        child: CustomAppbar(
          title: 'Edit Biodata',
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(18),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: const EdgeInsets.only(left: 12, right: 8),
              width: double.infinity,
              height: 50,
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.2),
                    spreadRadius: 1,
                    blurRadius: 9,
                    offset: const Offset(
                      1,
                      2,
                    ),
                  ),
                ],
              ),
              child: DropdownButtonHideUnderline(
                child: DropdownButton<String>(
                  items: agama.map((item) {
                    return DropdownMenuItem<String>(
                      value: item.nmAgama,
                      child: Text(item.nmAgama),
                    );
                  }).toList(),
                  onChanged: (newVal) {
                    setState(() {
                      _mySelection = newVal!;
                    });
                  },
                  value: _mySelection,
                ),
              ),
            ),

gmol1639

gmol16391#

使用状态管理或FutureBuilder从Future函数(生物数据提供者(). getBiodata())接收异步数据;)阅读更多信息:https://dart.dev/codelabs/async-awaithttps://docs.flutter.dev/development/data-and-backend

nlejzf6q

nlejzf6q2#

你正在使用List<Agama> agama = [];来显示下拉菜单项,但是你没有添加数据到你的agama列表.
因此,添加适当的数据到您的agama列表,您从API获得.
并且不要忘记在将数据添加到agama列表之后执行setState((){}),因为您没有使用任何状态管理。

kkbh8khc

kkbh8khc3#

这里有一个你想要的完整例子。

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter DropDownButton',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: const MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {
  String? dropdownvalue;

  Future<List<String>> getAllCategory() async {
    var baseUrl = "https://gssskhokhar.com/api/classes/";

    http.Response response = await http.get(Uri.parse(baseUrl));

    if (response.statusCode == 200) {
      List<String> items = [];
      var jsonData = json.decode(response.body) as List;
      for (var element in jsonData) {
        items.add(element["ClassName"]);
      }
      return items;
    } else {
      throw response.statusCode;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("DropDown List"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            FutureBuilder<List<String>>(
              future: getAllCategory(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  var data = snapshot.data!;
                  return DropdownButton(
                    // Initial Value
                    value: dropdownvalue ?? data[0],

                    // Down Arrow Icon
                    icon: const Icon(Icons.keyboard_arrow_down),

                    // Array list of items
                    items: data.map((String items) {
                      return DropdownMenuItem(
                        value: items,
                        child: Text(items),
                      );
                    }).toList(),
                    // After selecting the desired option,it will
                    // change button value to selected value
                    onChanged: (String? newValue) {
                      setState(() {
                        dropdownvalue = newValue!;
                      });
                    },
                  );
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ],
        ),
      ),
    );
  }
}

相关问题