如何在flutter中显示数据API

6yt4nkrj  于 2023-01-14  发布在  Flutter
关注(0)|答案(2)|浏览(136)

我正在尝试将数据显示到一个列表视图中,我已经设法从下面的响应控制台中获得数据,但数据没有出现在UI中,是不是我遗漏了什么,或者我的写作中有什么错误。谢谢。
这是我执行数据API调用的时候

class ListDosenProvider extends ChangeNotifier {
  static Future<List<ModelDosen>> getDosen() async {
    String url = Constant.baseURL;
    String token = await UtilSharedPreferences.getToken();
    final response = await http.get(
      Uri.parse(
        '$url/auth/mhs_siakad/dosen',
      ),
      headers: {
        'Authorization': 'Bearer $token',
      },
    );
    print(response.statusCode);
    print(response.body);
    if (response.statusCode == 200) {
      final List result = json.decode(response.body);
      return result.map((e) => ModelDosen.fromJson(e)).toList();
      // return ModelDosen.fromJson(jsonDecode(response.body));
    } else {
      throw Exception();
    }
  }
}

这是我在小部件内部调用它的时候

import 'package:flutter/material.dart';
import '../../../models/dosen/dosen_model.dart';
import '../../../provider/dosen/dosen_provider.dart';
import '../../../theme.dart';
import '../../../widgets/custom_appbar.dart';

class DosenPage extends StatefulWidget {
  const DosenPage({super.key});

  @override
  State<DosenPage> createState() => _DosenPageState();
}

class _DosenPageState extends State<DosenPage> {
  List<Datum> data = [];

  //  @override
  // void initState() {
  //   super.initState();
  //   fetchData();
  // }

  // fetchData() async {
  //   final apiResponse = await ListDosenProvider().getDosen() ??;
  //   setState(() {
  //     data = (apiResponse.data!);
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(kToolbarHeight),
        child: CustomAppbar(
          title: 'Dosen',
        ),
      ),
      body: Center(
        child: FutureBuilder<List<ModelDosen>>(
          future: ListDosenProvider.getDosen(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Expanded(
                child: ListView.builder(
                  itemCount: snapshot.data!.length,
                  itemBuilder: (context, index) {
                    return Container(
                      width: MediaQuery.of(context).size.width,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: const BorderRadius.all(
                          Radius.circular(8),
                        ),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.2),
                            spreadRadius: 1,
                            blurRadius: 9,
                            offset: const Offset(
                                1, 2), // changes position of shadow
                          ),
                        ],
                      ),
                      child: Padding(
                        padding: const EdgeInsets.all(14),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  data[index].name.toString(),
                                  style: bold6,
                                ),
                                Text(
                                  data[index].prodi.toString(),
                                  style: regular6,
                                ),
                                const SizedBox(
                                  height: 12,
                                ),
                                Row(
                                  children: [
                                    SizedBox(
                                      width: 94,
                                      height: 32,
                                      child: TextButton(
                                        onPressed: () {},
                                        style: TextButton.styleFrom(
                                          backgroundColor:
                                              const Color(0xffB3FFAE),
                                          shape: RoundedRectangleBorder(
                                            borderRadius:
                                                BorderRadius.circular(8),
                                          ),
                                        ),
                                        child: Text(
                                          "Email",
                                          style: boldButton1.copyWith(
                                            color: const Color(
                                              0xff379237,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                    const SizedBox(
                                      width: 8,
                                    ),
                                    SizedBox(
                                      width: 94,
                                      height: 32,
                                      child: TextButton(
                                        onPressed: (() {}),
                                        style: TextButton.styleFrom(
                                          backgroundColor:
                                              const Color(0xffC5D5FF),
                                          shape: RoundedRectangleBorder(
                                            borderRadius:
                                                BorderRadius.circular(8),
                                          ),
                                        ),
                                        child: Text(
                                          "Detail",
                                          style: boldButton2.copyWith(
                                            color: primaryColor,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                )
                              ],
                            ),
                            Image.asset(
                              'assets/images/user.png',
                              width: 50,
                            )
                          ],
                        ),
                      ),
                    );
                  },
                ),
              );
            } else {
              return CircularProgressIndicator(
                color: primaryColor,
              );
            }
          },
        ),
      ),
    );
  }
}

并且这是当调用API时的响应,响应也是OK 200

xuo3flqw

xuo3flqw1#

请将您的类替换为

class ListDosenProvider {
  static Future<List<Datum>> getDosen() async {
    String url =  Constant.baseURL;
    String token =
        await UtilSharedPreferences.getToken();
    final response = await https.get(
      Uri.parse(
        '$url/auth/mhs_siakad/dosen',
      ),
      headers: {
        'Authorization': 'Bearer $token',
      },
    );
  
    if (response.statusCode == 200) {
      final result = json.decode(response.body) as Map<String, dynamic>;

      ModelDosen dosen = ModelDosen.fromJson(result);

      List<Datum> l = dosen.data??[];

      return l;
    
    } else {
      throw Exception();
    }
  }
}

并更新您从Datum模型类中删除的?

class ModelDosen {
  ModelDosen({
    this.status,
    this.code,
    this.data,
  });
 
  String? status;
  String? code;
  List<Datum>? data;

Ui部分为

@override
  void initState() {
    super.initState();
    fabState.setFabStatus = FAB_STATUS.not_visible;
    fabState.setBottomNavStatus = NAV_STATUS.not_visible;
    getData();
  }

  Future<List<Datum>> getData() async {
    final result = await ListDosenProvider.getDosen();
    return result;
  }

 child: FutureBuilder<List<Datum>>(
                future: getData(),
                builder: (context, snapshot) {
                  if (snapshot.hasError) {
                    return Container(
                      child: const Text("error"),
                    );
                  } else if (snapshot.hasData) {
                    return Expanded(
                      child: ListView.builder(
                        itemCount: snapshot.data!.length,
                        itemBuilder: (context, index) {
                          return Container(
                            width: MediaQuery.of(context).size.width,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: const BorderRadius.all(
                                Radius.circular(8),
                              ),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.grey.withOpacity(0.2),
                                  spreadRadius: 1,
                                  blurRadius: 9,
                                  offset: const Offset(
                                      1, 2), // changes position of shadow
                                ),
                              ],
                            ),
                            child: Padding(
                              padding: const EdgeInsets.all(14),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        snapshot.data![index].name.toString(),
                                      ),
                                      Text(
                                        snapshot.data![index].prodi.toString(),
                                      ),
                                      const SizedBox(
                                        height: 12,
                                      ),
                                      Row(
                                        children: [
                                          SizedBox(
                                            width: 94,
                                            height: 32,
                                            child: TextButton(
                                              onPressed: () {},
                                              style: TextButton.styleFrom(
                                                backgroundColor:
                                                    const Color(0xffB3FFAE),
                                                shape: RoundedRectangleBorder(
                                                  borderRadius:
                                                      BorderRadius.circular(8),
                                                ),
                                              ),
                                              child: const Text(
                                                "Email",
                                              ),
                                            ),
                                          ),
                                          const SizedBox(
                                            width: 8,
                                          ),
                                          SizedBox(
                                            width: 94,
                                            height: 32,
                                            child: TextButton(
                                              onPressed: (() {}),
                                              style: TextButton.styleFrom(
                                                backgroundColor:
                                                    const Color(0xffC5D5FF),
                                                shape: RoundedRectangleBorder(
                                                  borderRadius:
                                                      BorderRadius.circular(8),
                                                ),
                                              ),
                                              child: const Text(
                                                "Detail",
                                              ),
                                            ),
                                          ),
                                        ],
                                      )
                                    ],
                                  ),
                                  Image.asset(
                                    'assets/images/user.png',
                                    width: 50,
                                  )
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    );
                  } else {
                    return const CircularProgressIndicator(
                      color: Colors.pink,
                    );
                  }
                },
              ),

5cg8jx4n

5cg8jx4n2#

如果要使用data变量,请确保从snapshot数据中分配该变量

FutureBuilder<List<ModelDosen>>(
                  future: ListDosenProvider.getDosen(),
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      
                      /// set the data
                      data = snapshot.data;

                      return ListView.builder(
                          itemCount: data.length,
                          itemBuilder: (context, index) {
                             return listTile(data[index]);
                          });
                    } else if (snapshot.hasError) {
                       /// Handle error
                    } else {
                      /// Show Progress Indicator
                    },
                   })

相关问题