简体   繁体   English

如何在颤振的下拉菜单中进行选择?

[英]How to make selection in dropdown in flutter?

I am implementing the Dropdown which is populated from API.我正在实现从 API 填充的下拉列表。 Data is populated successfully into the dropdown but when I select any item I am getting this error.数据已成功填充到下拉列表中,但是当我选择任何项目时,出现此错误。 Guys can anyone please help me?伙计们可以请任何人帮助我吗?

Error: There should be exactly one item with [DropdownButton]'s value: Instance of 'Make'.错误:应该只有一个具有 [DropdownButton] 值的项目:“Make”的实例。 Either zero or 2 or more [DropdownMenuItem]s were detected with the same value.检测到零个或 2 个或更多 [DropdownMenuItem] 具有相同的值。

FutureBuilder<List<Make>>(
                      future: _fetchBrand(),
                      builder: (BuildContext context,
                          AsyncSnapshot<List<Make>> snapshot) {
                        if (!snapshot.hasData) return CircularProgressIndicator();
                        return DropdownButtonFormField<Make>(
                          isDense: true,
                          decoration: spinnerDecoration('Select Car Brand'),
                          items: snapshot.data
                              .map((user) => DropdownMenuItem<Make>(
                            child: Text(user.make),
                            value: user,
                          ))
                              .toList(),
                          onChanged: (Make newVal) {
                            setState(() {
                              makeModel = newVal;
                            });
                          },
                          value: makeModel,
                        );
                      }),
Future<List<Make>> _fetchBrand() async {
    var response = await http.get(url);

    if (response.statusCode == 200) {
      final items = json.decode(response.body).cast<Map<String, dynamic>>();
      print(items);
      List<Make> listOfUsers = items.map<Make>((json) {
        return Make.fromJson(json);
      }).toList();

      return listOfUsers;
    } else {
      throw Exception('Failed to load internet');
    }
  }
class Make {
  String makeid;
  String make;

  Make(
      {this.makeid,
        this.make,});

  Make.fromJson(Map<String, dynamic> json) {
    makeid = json['makeid'];
    make = json['make'];
  }
}

You can copy paste run full code below您可以在下面复制粘贴运行完整代码
Reason原因
https://github.com/flutter/flutter/issues/11426#issuecomment-414047398 https://github.com/flutter/flutter/issues/11426#issuecomment-414047398
didUpdateWidget of the FutureBuilder state is being called every time a rebuild is issued.每次发布重建时都会调用 FutureBuilder 状态的 didUpdateWidget。 This function checks if the old future object is different from the new one此函数检查旧的未来对象是否与新的不同

Solution解决方案
You can declare a Future and init in initState and in FutureBuilder use this future您可以在initStateFutureBuilder声明Future和 init 使用此future

code snippet代码片段

Make makeModel = null;
Future _future;

@override
  void initState() {
    _future = _fetchBrand();
    super.initState();
  }

body: FutureBuilder<List<Make>>(
          future: _future,  

working demo工作演示

在此处输入图片说明

full code完整代码

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

class Make {
  String makeid;
  String make;

  Make({
    this.makeid,
    this.make,
  });

  Make.fromJson(Map<String, dynamic> json) {
    makeid = json['makeid'];
    make = json['make'];
  }
}

void main() => runApp(MyApp());

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

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Make makeModel = null;
  Future _future;
  Future<List<Make>> _fetchBrand() async {
    String response = '''
    [
{
    "makerid" : "a",
    "make" : "a1"
},
{
    "makerid" : "b",
    "make" : "b1"
}
]
    ''';

    final items = json.decode(response).cast<Map<String, dynamic>>();
    print(items);
    List<Make> listOfUsers = items.map<Make>((json) {
      return Make.fromJson(json);
    }).toList();

    return listOfUsers;

    /*var response = await http.get(url);

    if (response.statusCode == 200) {
      final items = json.decode(response.body).cast<Map<String, dynamic>>();
      print(items);
      List<Make> listOfUsers = items.map<Make>((json) {
        return Make.fromJson(json);
      }).toList();

      return listOfUsers;
    } else {
      throw Exception('Failed to load internet');
    }*/
  }

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  void initState() {
    _future = _fetchBrand();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: FutureBuilder<List<Make>>(
          future: _future,
          builder: (BuildContext context, AsyncSnapshot<List<Make>> snapshot) {
            if (!snapshot.hasData) return CircularProgressIndicator();
            return DropdownButtonFormField<Make>(
              isDense: true,
              decoration: InputDecoration(
                  fillColor: Colors.blue.shade100,
                  filled: true,
                  labelText: 'Select Car Brand'),
              items: snapshot.data
                  .map((user) => DropdownMenuItem<Make>(
                        child: Text(user.make),
                        value: user,
                      ))
                  .toList(),
              onChanged: (Make newVal) {
                setState(() {
                  print(newVal.toString());
                  makeModel = newVal;
                });
              },
              value: makeModel,
            );
          }),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM