// ignore_for_file: prefer_const_constructors, avoid_unnecessary_containers, prefer_const_literals_to_create_immutables, import_of_legacy_library_into_null_safe, non_constant_identifier_names, unused_field, avoid_print
import 'dart:convert';
import 'package:dropdownfield/dropdownfield.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class FoodWidget extends StatefulWidget {
const FoodWidget({Key? key}) : super(key: key);
@override
_FoodWidgetState createState() => _FoodWidgetState();
}
class _FoodWidgetState extends State<FoodWidget> {
@override
void initState() {
fetchFood();
super.initState();
}
String? food_id;
List food = [];
Future<void> fetchFood() async {
final String response =
await rootBundle.loadString('assets/list_food.json');
final data = await json.decode(response);
print(data);
setState(() {
food = data["food"];
});
}
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(15.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
DropDownField(
onValueChanged: (dynamic value) {
food_id = value;
},
value: food_id,
required: false,
labelText: 'Search food',
items: food,
),
]),
);
}
}
,这是JSON文件。我想在DropDownField中只获取名称,但我做不到。对于setState函数,我真的不知道该怎么写。
{
"food": [
{
"id": 1,
"name": "coca-cola",
"calories": 120
},
{
"id": 2,
"name": "egg",
"calories": 80
},
{
"id": 3,
"name": "rice",
"calories": 100
}
]
}
我试着打印(数据)来测试输出。这些都来自域名,但我想在里面使用。我真的不知道该怎么做。
p。我真的很感激你的回答和建议。
您只需要映射数据以获得其名称:
Future<void> fetchFood() async {
final String response =
await rootBundle.loadString('assets/list_food.json');
final data = await json.decode(response);
print(data);
setState(() {
food = data["food"].map((e)=>e['name']).toList();
});
}
在获得食物列表后,您将每个项目映射为只获得您需要的食物名称。
作为旁注
我建议你以后创建这样一个模型:
class Food {
Food({
this.id,
this.name,
this.calories,
});
int id;
String name;
int calories;
factory Food.fromJson(Map<String, dynamic> json) => Food(
id: json["id"],
name: json["name"],
calories: json["calories"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"calories": calories,
};
}
所以你有一个强类型的List<Food> food
,你可以在类型安全的情况下访问参数。
您需要生成Food类
class Food {
String? id;
String? name;
String? calories;
Food({
this.id,
this.name,
this.calories,
});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'calories': calories,
};
}
factory Food.fromMap(Map<String, dynamic> map) {
return Food(
id: map['id'],
name: map['name'],
calories: map['calories'],
);
}
String toJson() => json.encode(toMap());
factory Food.fromJson(String source) => Food.fromMap(json.decode(source));
}
完整代码在这里:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class FoodWidget extends StatefulWidget {
const FoodWidget({Key? key}) : super(key: key);
@override
_FoodWidgetState createState() => _FoodWidgetState();
}
class _FoodWidgetState extends State<FoodWidget> {
@override
void initState() {
fetchFood();
super.initState();
}
String? food_id;
Food? selected_food ;
List<Food> food = [];
Future<void> fetchFood() async {
final String response =
await rootBundle.loadString('assets/list_food.json');
final data = await json.decode(response) as List;
print(data);
setState(() {
food = data.map((e) => Food.fromJson(e)).toList();
});
}
@override
Widget build(BuildContext context) {
return Container(
padding:const EdgeInsets.all(15.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
DropdownButton<Food>(
focusColor: Colors.white,
value: selected_food,
//elevation: 5,
style: const TextStyle(color: Colors.white),
iconEnabledColor: Colors.black,
underline: const SizedBox.shrink(),
items: food.map<DropdownMenuItem<Food>>(
(Food value) {
return DropdownMenuItem<Food>(
value: value,
child: Text(
value.name!,
style: const TextStyle(color: Colors.black),
),
);
}).toList(),
hint: const Text(
"Select Shop Category",
style: TextStyle(
color: Colors.black38,
),
),
onChanged: (Food? value) {
setState(() {
selected_food= value!;
});
},
),
]),
);
}
}
class Food {
String? id;
String? name;
String? calories;
Food({
this.id,
this.name,
this.calories,
});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'calories': calories,
};
}
factory Food.fromMap(Map<String, dynamic> map) {
return Food(
id: map['id'],
name: map['name'],
calories: map['calories'],
);
}
String toJson() => json.encode(toMap());
factory Food.fromJson(String source) =>
Food.fromMap(json.decode(source));
}