flutter - 在颤振地图功能在列小部件中不起作用
问题描述
我正在尝试在列小部件内动态创建行小部件。我是新手,我尽力了,但仍然未能解决问题。我想请你帮我解决这个问题。我添加了所有我尝试过的东西。非常感谢
我的杰森
{
"status": true,
"data": {
"id": 1,
"image": "https://img.taste.com.au/fruCLEZM/taste/2019/08/chicken-karahi-153167-2.jpg",
"calories": 100,
"ingredients_count": 5,
"serve": 1,
"views": 1,
"time": 1,
"translate": {
"post_title": "Chicken Karahi",
"post_description": "spicy and tasteful chicken karahi."
},
"ingredients": [
{
"name": "yogurt",
"quantity": "1 cup",
"image": "https://www.archanaskitchen.com/images/archanaskitchen/BasicRecipes_HOW_TO/How_To_Make_Fresh_Homemade_Yogurt_Curd_400.jpg"
},
{
"name": "red chilli",
"quantity": "100 gram",
"image": "https://ik.imagekit.io/91ubcvvnh3k/tr:w-500/https://www.planetorganic.com//images/products/medium/26148.jpg"
}
]
}
}
我面临两个错误,如下所示,
Another exception was thrown: type '(dynamic) => dynamic' is not a subtype of type '(Ingredient) => Widget' of 'f'
和
type 'Container' is not a subtype of type 'List<Widget>'
在我的全班课程中,我有以下
var posts;
bool _load = false;
void initState() {
super.initState();
getRecipeById().then((value) => {
setState((){
posts = value;
})
});
}
通过这种方法,我从 api 获取数据
getRecipeById() async {
String url = 'http://www.xxxxx.com/xxxxx/in.php';
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Accept': '*/*',
};
final json = {
"by_post_id": 'yes',
"post_id":'${widget.postId}'
};
http.Response response = await http.post(url, body: json);
if(response.statusCode == 200){
setState(() {
_load = true;
});
}
var jsonResponse = jsonDecode(response.body);
posts = RecipeModel.fromJson(jsonResponse['data']);
return posts;
}
以下是我的构建小部件
Widget build(BuildContext context) {
final ingredientsList = Container(
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.only(left: 1.0, right: 25.0),
margin: const EdgeInsets.only(bottom: 20.0),
child: Container(
child: Column(
children: (_load == false) ? Container(child:Text("loading..")) : posts.ingredients.map<Widget>((data) =>
ingredientsRow(data.name, data.quantity, data.image)
).toList(),
),
),
);
return SafeArea(
top: true,
child: Scaffold(
body: Directionality(
textDirection: TextDirection.ltr,
child: SingleChildScrollView(
child: (_load == false) ? Container(
alignment: Alignment.center,
child: Text("loading now..")
) :
Column(
children: <Widget>[
ingredientsList,
],
),
),
),
)
);
}
以下是我想在地图中使用的功能
ingredientsRow(name, quantity, image)
{
return Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Expanded(
flex: 2, // 20%
child: Container(
alignment: Alignment.center,
child: Image.network(image,
height: 45,
)
),
),
Expanded(
flex: 4, // 60%
child: Container(
child:Text(
name,
style: TextStyle(
color: Color(0xff41453c),
fontSize: 15,
fontWeight: FontWeight.w400
),
)
),
),
Expanded(
flex: 4, // 20%
child: Container(
alignment: Alignment.center,
child:Text(
quantity,
style: TextStyle(
color: Color(0xff41453c),
fontSize: 15,
fontWeight: FontWeight.w400
),
)
),
)
],
);
}
这是我的数据模型类
class RecipeModel{
final int id;
final String image;
final List<Ingredient> ingredients;
RecipeModel({this.id, this.image, this.ingredients});
factory RecipeModel.fromJson(Map<String, dynamic> parsedJson){
var list = parsedJson['ingredients'] as List;
print(list.runtimeType);
List<Ingredient> ingredientsList = list.map((i) => Ingredient.fromJson(i)).toList();
return RecipeModel(
id: parsedJson['id'],
image: parsedJson['image'],
ingredients: ingredientsList
);
}
}
class Ingredient {
final String name;
final String quantity;
final String image;
Ingredient({this.name, this.quantity, this.image});
factory Ingredient.fromJson(Map<String, dynamic> parsedJson){
return Ingredient(
name:parsedJson['name'],
quantity:parsedJson['quantity'],
image:parsedJson['image']
);
}
}
解决方案
最好的方法是使用FutureBuilder。
我检查了您的代码,主要更改了 4 件事:
1-我使用了FutureBuilder的方法,它是为此目的而构建的。
2-删除了成分列表变量,并将其代码移至名为 _buildIngredientList 的函数,返回类型为 Widget。
3-删除 bool 变量,因为不再需要使用 FutureBuilder。
4- 将返回类型“Widget”添加到 ingredientsRow 函数中,否则会引发类型错误。
查看下面的代码:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:stackoverflowsamples/models.dart';
void main() => runApp(
MaterialApp(home: HomePage(),
theme: ThemeData.fallback(),
),
);
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var posts;
///3 - Remove bool
void initState() {
super.initState();
getRecipeById().then((value) => {
setState((){
posts = value;
})
});
}
Widget build(BuildContext context) {
return SafeArea(
top: true,
child: Scaffold(
body: Directionality(
textDirection: TextDirection.ltr,
child: SingleChildScrollView(
child:
FutureBuilder( ///1
future: getRecipeById(),
builder: (context, snapshot) {
if(snapshot.connectionState == ConnectionState.done) {
return Column(
children: <Widget>[
_buildIngredientList(),
],
);
} else {
return Container(
alignment: Alignment.center,
child: Text("loading now..")
);
}
}
),
),
),
)
);
}
Widget _buildIngredientList() { ///2
return Container(
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.only(left: 1.0, right: 25.0),
margin: const EdgeInsets.only(bottom: 20.0),
child: Container(
child: Column(
children: posts.ingredients.map<Widget>((data) =>
ingredientsRow(data.name, data.quantity, data.image)
).toList(),
),
),
);
}
///4
Widget ingredientsRow(name, quantity, image) {
return Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Expanded(
flex: 2, // 20%
child: Container(
alignment: Alignment.center,
child: Image.network(image,
height: 45,
)
),
),
Expanded(
flex: 4, // 60%
child: Container(
child:Text(
name,
style: TextStyle(
color: Color(0xff41453c),
fontSize: 15,
fontWeight: FontWeight.w400
),
)
),
),
Expanded(
flex: 4, // 20%
child: Container(
alignment: Alignment.center,
child:Text(
quantity,
style: TextStyle(
color: Color(0xff41453c),
fontSize: 15,
fontWeight: FontWeight.w400
),
)
),
)
],
);
}
getRecipeById() async {
///I've pasted the json as literal here because otherwise I couldn't make it run on my side.
var jsonResponse = jsonDecode('''{
"status": true,
"data": {
"id": 1,
"image": "https://img.taste.com.au/fruCLEZM/taste/2019/08/chicken-karahi-153167-2.jpg",
"calories": 100,
"ingredients_count": 5,
"serve": 1,
"views": 1,
"time": 1,
"translate": {
"post_title": "Chicken Karahi",
"post_description": "spicy and tasteful chicken karahi."
},
"ingredients": [
{
"name": "yogurt",
"quantity": "1 cup",
"image": "https://www.archanaskitchen.com/images/archanaskitchen/BasicRecipes_HOW_TO/How_To_Make_Fresh_Homemade_Yogurt_Curd_400.jpg"
},
{
"name": "red chilli",
"quantity": "100 gram",
"image": "https://ik.imagekit.io/91ubcvvnh3k/tr:w-500/https://www.planetorganic.com//images/products/medium/26148.jpg"
}
]
}
}''');
posts = RecipeModel.fromJson(jsonResponse['data']);
return posts;
}
}
推荐阅读
- python-3.x - 使用多处理时进程冻结
- python - 在列表中打印元组
- c# - 控制台应用程序字符串输出到另一个 Web 应用程序文本框
- python - 每次在代码中使用变量时评估它
- css - 如何将 styled-component 样式附加到组件 className 道具?
- python - 如何在python中使用列表理解来等于多个变量?
- javascript - 如何将 JSON 对象传递给角度自定义元素
- mysql - MySQL 表连接不一致
- android-studio - 如何从 Spinner 中选择项目然后在按钮单击时执行某些操作?
- aws-lambda - AWS Lex:没有在控制台上创建后续提示的选项