【问题标题】:How to make selection in dropdown in flutter?如何在颤动的下拉列表中进行选择?
【发布时间】:2020-06-10 17:32:20
【问题描述】:

我正在实现从 API 填充的下拉菜单。数据已成功填充到下拉列表中,但是当我选择任何项目时出现此错误。各位大神可以帮帮我吗?

错误:应该只有一项具有 [DropdownButton] 的值:“Make”的实例。 检测到 0 个或 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'];
  }
}

【问题讨论】:

  • 你能分享你的示例json吗?

标签: android ios flutter dart


【解决方案1】:

您可以在下面复制粘贴运行完整代码
原因
https://github.com/flutter/flutter/issues/11426#issuecomment-414047398
每次发出重建时都会调用 FutureBuilder 状态的 didUpdateWidget。此函数检查旧的未来对象是否与新的不同

解决方案
您可以声明 Future 并在 initStateFutureBuilder 中初始化使用 future

代码sn-p

Make makeModel = null;
Future _future;

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

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

工作演示

完整代码

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),
      ),
    );
  }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
相关资源
最近更新 更多