Flutter 如何使用Flatter FutureBuilder构建下拉菜单

Flutter 如何使用Flatter FutureBuilder构建下拉菜单,flutter,dart,flutter-layout,Flutter,Dart,Flutter Layout,嗨,我想在颤振中使用FutureBuilder构建下拉菜单,因为我从API获取json,我在颤振中是新手,所以我尝试了,但我做不到 这是我的密码 Future<Album> fetchAlbum() async { final response = await http.get( 'https://vpic.nhtsa.dot.gov/api/vehicles/getmodelsformake/honda?format=json'); if (respon

嗨,我想在颤振中使用FutureBuilder构建下拉菜单,因为我从API获取json,我在颤振中是新手,所以我尝试了,但我做不到 这是我的密码

   Future<Album> fetchAlbum() async {
  final response = await http.get(
      'https://vpic.nhtsa.dot.gov/api/vehicles/getmodelsformake/honda?format=json');

  if (response.statusCode == 200) {
    return Album.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Failed to load album');
  }
}

class Album {
  int count;
  String message;
  String searchCriteria;
  List<Results> results;

  Album({this.count, this.message, this.searchCriteria, this.results});

  Album.fromJson(Map<String, dynamic> json) {
    count = json['Count'];
    message = json['Message'];
    searchCriteria = json['SearchCriteria'];
    if (json['Results'] != null) {
      results = new List<Results>();
      json['Results'].forEach((v) {
        results.add(new Results.fromJson(v));
      });
    }
  }
}

class Results {
  int makeID;
  String makeName;
  int modelID;
  String modelName;

  Results({this.makeID, this.makeName, this.modelID, this.modelName});

  Results.fromJson(Map<String, dynamic> json) {
    makeID = json['Make_ID'];
    makeName = json['Make_Name'];
    modelID = json['Model_ID'];
    modelName = json['Model_Name'];
  }
}
Future fetchAlbum()异步{
最终响应=等待http.get(
'https://vpic.nhtsa.dot.gov/api/vehicles/getmodelsformake/honda?format=json');
如果(response.statusCode==200){
返回Album.fromJson(jsonDecode(response.body));
}否则{
抛出异常(“加载相册失败”);
}
}
班级相册{
整数计数;
字符串消息;
字符串搜索条件;
列出结果;
相册({this.count,this.message,this.searchCriteria,this.results});
fromJson(映射json){
count=json['count'];
message=json['message'];
searchCriteria=json['searchCriteria'];
如果(json['Results']!=null){
结果=新列表();
json['Results'].forEach((v){
results.add(newresults.fromJson(v));
});
}
}
}
课堂成绩{
int-makeID;
字符串生成名;
int modelID;
字符串模型名;
结果({this.makeID,this.makeName,this.modelID,this.modelName});
Results.fromJson(映射json){
makeID=json['Make_ID'];
makeName=json['Make_Name'];
modelID=json['Model_ID'];
modelName=json['Model_Name'];
}
}
我想为所有modelID构建一个DropDownMenuList


谢谢

未经测试,但这应该可以工作

FutureBuilder<Album>(
      future: fetchAlbum(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          final album = snapshot.data;
          final results = album.results;
          return DropdownButton<Results>(
              items: results.map((result) {
                return DropdownMenuItem<Results>(
                  value: result,
                  child: Text('${result.modelID}'),
                );
              }).toList(),
              onChanged: (album) {
                // selected album
              });
        } else
          return CircularProgressIndicator();
      });
FutureBuilder(
future:fetchAlbum(),
生成器:(上下文,快照){
if(snapshot.hasData){
最终相册=snapshot.data;
最终结果=album.results;
返回下拉按钮(
项目:results.map((结果){
返回下拉菜单项(
价值:结果,
子项:文本(“${result.modelID}”),
);
}).toList(),
更改:(相册){
//精选专辑
});
}否则
返回循环ProgressIndicator();
});

您可以复制粘贴运行下面的完整代码
代码片段

FutureBuilder(
      future: _future,
      builder: (context, AsyncSnapshot<Album> snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.none:
            return Text('none');
          case ConnectionState.waiting:
            return Center(child: CircularProgressIndicator());
          case ConnectionState.active:
            return Text('');
          case ConnectionState.done:
            if (snapshot.hasError) {
              return Text(
                '${snapshot.error}',
                style: TextStyle(color: Colors.red),
              );
            } else {
              return DropdownButton<Results>(
                isExpanded: true,
                items:
                    snapshot.data.results.map((Results dropDownStringItem) {
                  return DropdownMenuItem<Results>(
                    value: dropDownStringItem,
                    child: Text(dropDownStringItem.modelID.toString()),
                  );
                }).toList(),
                onChanged: (value) {
                  setState(() {
                    _selected = value;
                  });
                },
                value: _selected,
              );
            }
        }
      })
FutureBuilder(
未来:未来,
生成器:(上下文,异步快照)

完整代码

import 'dart:convert';

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

class Album {
  int count;
  String message;
  String searchCriteria;
  List<Results> results;

  Album({this.count, this.message, this.searchCriteria, this.results});

  Album.fromJson(Map<String, dynamic> json) {
    count = json['Count'];
    message = json['Message'];
    searchCriteria = json['SearchCriteria'];
    if (json['Results'] != null) {
      results = [];
      json['Results'].forEach((v) {
        results.add(new Results.fromJson(v));
      });
    }
  }
}

class Results {
  int makeID;
  String makeName;
  int modelID;
  String modelName;

  Results({this.makeID, this.makeName, this.modelID, this.modelName});

  Results.fromJson(Map<String, dynamic> json) {
    makeID = json['Make_ID'];
    makeName = json['Make_Name'];
    modelID = json['Model_ID'];
    modelName = json['Model_Name'];
  }
}

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> {
  Future<Album> _future;
  Results _selected;

  Future<Album> fetchAlbum() async {
    final response = await http.get(
        'https://vpic.nhtsa.dot.gov/api/vehicles/getmodelsformake/honda?format=json');

    if (response.statusCode == 200) {
      return Album.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Failed to load album');
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: FutureBuilder(
          future: _future,
          builder: (context, AsyncSnapshot<Album> snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none:
                return Text('none');
              case ConnectionState.waiting:
                return Center(child: CircularProgressIndicator());
              case ConnectionState.active:
                return Text('');
              case ConnectionState.done:
                if (snapshot.hasError) {
                  return Text(
                    '${snapshot.error}',
                    style: TextStyle(color: Colors.red),
                  );
                } else {
                  return DropdownButton<Results>(
                    isExpanded: true,
                    items:
                        snapshot.data.results.map((Results dropDownStringItem) {
                      return DropdownMenuItem<Results>(
                        value: dropDownStringItem,
                        child: Text(dropDownStringItem.modelID.toString()),
                      );
                    }).toList(),
                    onChanged: (value) {
                      setState(() {
                        _selected = value;
                      });
                    },
                    value: _selected,
                  );
                }
            }
          }),
    );
  }
}
导入'dart:convert';
进口“包装:颤振/材料.省道”;
将“package:http/http.dart”导入为http;
班级相册{
整数计数;
字符串消息;
字符串搜索条件;
列出结果;
相册({this.count,this.message,this.searchCriteria,this.results});
fromJson(映射json){
count=json['count'];
message=json['message'];
searchCriteria=json['searchCriteria'];
如果(json['Results']!=null){
结果=[];
json['Results'].forEach((v){
results.add(newresults.fromJson(v));
});
}
}
}
课堂成绩{
int-makeID;
字符串生成名;
int modelID;
字符串模型名;
结果({this.makeID,this.makeName,this.modelID,this.modelName});
Results.fromJson(映射json){
makeID=json['Make_ID'];
makeName=json['Make_Name'];
modelID=json['Model_ID'];
modelName=json['Model_Name'];
}
}
void main(){
runApp(MyApp());
}
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
标题:“颤振演示”,
主题:主题数据(
主样本:颜色。蓝色,
),
主页:MyHomePage(标题:“颤振演示主页”),
);
}
}
类MyHomePage扩展StatefulWidget{
MyHomePage({Key,this.title}):超级(Key:Key);
最后的字符串标题;
@凌驾
_MyHomePageState createState()=>\u MyHomePageState();
}
类_MyHomePageState扩展状态{
未来,未来;;
结果:入选;
Future fetchAlbum()异步{
最终响应=等待http.get(
'https://vpic.nhtsa.dot.gov/api/vehicles/getmodelsformake/honda?format=json');
如果(response.statusCode==200){
返回Album.fromJson(jsonDecode(response.body));
}否则{
抛出异常(“加载相册失败”);
}
}
@凌驾
void initState(){
_future=fetchAlbum();
super.initState();
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(widget.title),
),
正文:未来建设者(
未来:未来,
生成器:(上下文,异步快照){
交换机(快照.连接状态){
案例连接状态。无:
返回文本(“无”);
案例连接状态。正在等待:
返回中心(子项:CircularProgressIndicator());
案例连接状态.active:
返回文本(“”);
案例连接状态。完成:
if(snapshot.hasError){
返回文本(
“${snapshot.error}”,
样式:TextStyle(颜色:Colors.red),
);
}否则{
返回下拉按钮(
是的,
项目:
snapshot.data.results.map((results dropDownStringItem){
返回下拉菜单项(
值:dropDownStringItem,
子项:文本(dropDownStringItem.modelID.toString()),
);
}).toList(),
一旦更改:(值){
设置状态(){
_所选=值;
});
},
值:_已选定,
);
}
}
}),
);
}
}