Ffltter:以字典列表的形式从API中获取数据,并在Dropdown Button中显示

bvjxkvbb  于 2022-10-09  发布在  Android
关注(0)|答案(1)|浏览(139)

我还是个初学者,我正在试着把API数据放到Fflight中去。该接口包含List<Maps>``"responseObj"key``value对。我想在应用程序启动时获取数据并将其显示到DropdownButton中,即initState()。我希望我的输出如下所示:

以下是接口:http://161.97.96.193:3333/LovLeaveRequest

以下是我的代码:

import 'dart:convert';

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

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

class _MyHomePageState extends State<MyHomePage> {
  String? value;
  List<String> leaveRequest = [];

  Future<List> get() async {
    var response = await http.get(
      Uri.parse("http://161.97.96.193:3333/LovLeaveRequest"),
    );
    if (response.statusCode == 200) {
      final jsonData = jsonDecode(response.body);
      return jsonData["responseObj"];
    } else {
      throw Exception();
    }
  }

  @override
  void initState() {
    // leaveRequest = get();
    get();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: DropdownButton<String>(
            hint: Text('Select Type'),
            value: this.value,
            items: leaveRequest.map((item) {
              return DropdownMenuItem(
                child: Text(item),
                value: item,
              );
            }).toList(),
            onChanged: (value) {
              setState(() {
                this.value = value;
              });
            },
          ),
        ),
      ),
    );
  }
}

我在initState()中的注解行遇到的问题是A value of type 'Future<List<dynamic>>' can't be assigned to a variable of type 'List<String>'. Try changing the type of the variable, or casting the right-hand type to 'List<String>'.

p5fdfcr1

p5fdfcr11#

获取API响应是一项艰巨的工作。*如果您使用普通的json响应,则更难维护您的代码,并且您的代码将变成Spaghetti Code。*因此,处理它的最简单方法是生成一个在JSON格式之间相互转换的模型类。

建议您看看JSON序列化。

此外,在获取数据时,你应该显示一个圆形或线性的加载条,这样用户就不会被应用程序冻结搞混了。这是我修改过的代码。

import 'dart:convert';

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

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

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

class _MyHomePageState extends State<MyHomePage> {
  String? value;
  bool loading = true;
  List<ApiResponse> leaveRequest = [];

  void get() async {
    var response = await http.get(
      Uri.parse("http://161.97.96.193:3333/LovLeaveRequest"),
    );
    if (response.statusCode == 200) {
      final jsonData = jsonDecode(response.body);
      List<dynamic> data = jsonData["responseObj"];
      for (dynamic d in data) {
        leaveRequest.add(ApiResponse.fromJson(d));
      }
      setState(() {
        loading = false;
      });
    } else {
      throw Exception();
    }
  }

  @override
  void initState() {
    get();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox(
        child: Center(
          child: loading
              ? CircularProgressIndicator()
              : DropdownButton<String>(
                  hint: const Text('Select Type'),
                  value: value,
                  items: leaveRequest.map((item) {
                    return DropdownMenuItem(
                      value: item.value,
                      child: Text(item.value),
                    );
                  }).toList(),
                  onChanged: (val) {
                    setState(() {
                      value = val;
                    });
                  },
                ),
        ),
      ),
    );
  }
}

class ApiResponse {
  ApiResponse({
    required this.key,
    required this.value,
  });

  int key;
  String value;

  factory ApiResponse.fromJson(Map<String, dynamic> json) => ApiResponse(
        key: json["Key"],
        value: json["Value"],
      );

  Map<String, dynamic> toJson() => {
        "Key": key,
        "Value": value,
      };
}

**这里是额外的部分。**当在initState方法中调用异步方法时,应该这样调用

快乐编码TT

@override
void initState(){
super.initState();
 WidgetsBinding.instance.addPostFrameCallback((_){
    *yourAsyncMethod();   });
}

相关问题