带有未来构建器的Flutter下拉列表

ijxebb2r  于 2023-01-27  发布在  Flutter
关注(0)|答案(3)|浏览(109)

这是我的数据模型

class RoleModel {
  int? id;
  String? role;

  RoleModel({this.id, this.role});
  RoleModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    role = json['role'];
  }
  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = id;
    data['role'] = role;
    return data;
  }
}

这是我获取API数据的代码

List<RoleModel> roles = [];

  Future<List<RoleModel>> getRoles() async {
    try {
      final response = await http
          .get(Uri.parse('https://localhost:8000/roles'));
      var data = jsonDecode(response.body.toString());
      if (response.statusCode == 200) {
        for (Map<String, dynamic> i in data) {
          roles.add(RoleModel.fromJson(i));
        }
        return roles;
      } else {
        throw Exception('Failed to load roles:$response');
      }
    } catch (e) {
      throw Exception('Failed due to: $e');
    }
  }

我怎样才能创建一个下拉按钮,它将有'id'作为值和'role'将显示为文本?

nfzehxib

nfzehxib1#

您可以使用下拉小部件的示例代码行下方的

DropdownButton<String>(
          items: <String>['One', 'Two', 'Three', 'Four'].map((String value) {
            return DropdownMenuItem<String>(
              value: value,
              child: Text(value),
            );
          }).toList(),
          onChanged: (v) {},
        ),

niwlg2el

niwlg2el2#

您可以像这样创建它

DropdownButton<int>(
          items: [
            DropdownMenuItem(
              child: Text("${roleModel.role}"),
              value: roleModel.id,
            ),
          ],
          onChanged: (value) {},
        ),
8dtrkrch

8dtrkrch3#

您还可以使用www.example.com上的自定义包创建下拉按钮pub.dev:
1.从[1]将最新版本的dropdown_button2添加到pubspec.yaml文件中:https://pub.dev/packages/dropdown_button2/install
1.从您的终端运行'flutter pub add dropdown_button2'这个命令。
1.添加'导入'包:下拉按钮2/下拉按钮2.dart ';这一行添加到代码页。

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

    void main() => runApp(MyFlutterApp());
    
    class MyFlutterApp extends StatelessWidget {
      const MyFlutterApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          home: HomePage(),
        );
      }
    }
    
    class HomePage extends StatefulWidget {
      const HomePage({super.key});
    
      @override
      State<HomePage> createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
      @override
      
    
      List<String> get getAllRoles {
        List<String> allRoles = [];
        for (int i = 0; i < roles.length; i++) {
          allRoles.add('${roles[i].id}    ${roles[i].role}');
        }
        return allRoles; // String format of json taken from the web.
      }
    
      int index = 0;
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('Dropdown with id and role'),
          ),
          body: Padding(
            padding: const EdgeInsets.all(8.0),
            child: CustomDropdownButton2(
              hint: 'Select Item',
              dropdownItems: getAllRoles,
              value: getAllRoles[index],
              buttonWidth: double.infinity,
              dropdownWidth: double.infinity,
              buttonElevation: 7,
              onChanged: (value) {
                setState(() {
                  index = getAllRoles.indexOf(value.toString());
                });
              },
            ),
          ),
        );
      }
    }
    
    class RoleModel {
      int? id;
      String? role;
    
      RoleModel({this.id, this.role});
      RoleModel.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        role = json['role'];
      }
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = <String, dynamic>{};
        data['id'] = id;
        data['role'] = role;
        return data;
      }
    }
    
    List<RoleModel> roles = [];
    
    Future<List<RoleModel>> getRoles() async {
      try {
        final response = await http.get(Uri.parse('https://localhost:8000/roles'));
        var data = jsonDecode(response.body.toString());
        if (response.statusCode == 200) {
          for (Map<String, dynamic> i in data) {
            roles.add(RoleModel.fromJson(i));
          }
          return roles;
        } else {
          throw Exception('Failed to load roles:$response');
        }
      } catch (e) {
        throw Exception('Failed due to: $e');
      }
    }

我收到了一个错误,因为http的网址现在无法访问。如果你尝试用一个新的网址,我认为这段代码将正常工作。

相关问题