【发布时间】:2021-12-26 19:27:33
【问题描述】:
我想访问items 以在小部件内部使用以生成项目列表。我该怎么做?我是新来的。这是将生成列表的小部件的完整代码。这是我从昨天开始就无法弄清楚的问题。我希望得到启发。
class Breakfast extends StatefulWidget {
Breakfast({
Key? key,
}) : super(key: key);
@override
_BreakfastState createState() => _BreakfastState();
}
class _BreakfastState extends State<Breakfast> {
Future<String> _loadloadBreakfastAsset() async {
return await rootBundle.loadString('assets/breakfast.json');
}
Future<List<Breakfast>> loadBreakfast() async{
String jsonAddress = await _loadloadBreakfastAsset();
Map<String,dynamic> map = json.decode(jsonAddress);
List<dynamic> items = map["items"];
// This return value is thrown away, but this line is necessary to
// resolve the Future call that FutureBuilder is waiting on.
return Future<List<Breakfast>>.value();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: loadBreakfast(),
builder: (BuildContext, AsyncSnapshot<dynamic>snapshot){
return Column(
children: [
Padding(
padding:
EdgeInsets.symmetric(horizontal: getProportionateScreenWidth(20)),
child: SectionTitle(title: "Choices", press: () {}),
),
SizedBox(height: getProportionateScreenWidth(20)),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
...List.generate(
snapshot.data![index].length,
(index) {
if (items[index].isPopular) {
return BreakfastCard(breakfast: items[index]);
}
return const SizedBox
.shrink(); // here by default width and height is 0
},
),
SizedBox(width: getProportionateScreenWidth(20)),
],
),
)
],
);
});
}
}
这是 JSON 数据 ....
{
"items": [{
"id": 1,
"rating": "4.7",
"images": [
"assets/images/egg.png"
],
"title": "Fried Egg",
"description": "Sunny",
"isFavorite": false,
"isPopular": true,
"serving": 1
}, {
"id": 2,
"rating": "4.0",
"images": [
"assets/images/longanisa.png"
],
"title": "Longanisa",
"description": "Yum",
"isFavorite": false,
"isPopular": false,
"serving": 3
}
]
}
【问题讨论】:
-
您是否将其用作
FutureBuilder的未来?然后不是返回Future<Breakfast>.value();,而是返回items。 -
当我尝试退货时,错误是这样的:
A value of type 'List<dynamic>' can't be returned from the method 'loadBreakfast' because it has a return type of 'Future<Breakfast>'. -
可以加入
Breakfast模型吗?
标签: flutter dart jsonparser flutter-futurebuilder