我是 dart 编程新手。 我发现了一个关于我的问题的错误,即“我创建了一个模型类和一个列表,模型类有一个 Color 类型的成员,然后在 main.dart 中,我想在 ListView.builder 中显示我的模型数据列表,但是当在容器的单独小部件中时,其他一切都运行良好,但颜色属性给出错误,我尝试更改类型索引参数,但错误仍然存在。”
这里是代码:
import 'package:flutter/material.dart';
class ProductModel {
ProductModel(
this.title,
this.name,
this.image,
this.color
);
final String title;
final String name;
final String image;
final Color color;
}
final modelProduct = <ProductModel>[
ProductModel(
"titile1",
"name1",
"https://image.freepik.com/free-vector/multitasking-concept-illustration-character_23-2148403716.jpg",
Colors.pink.withOpacity(0.4),
),
ProductModel(
"titile2",
"name2",
"https://image.freepik.com/free-vector/people-putting-puzzle-pieces-together_52683-28610.jpg",
Colors.blue.withOpacity(0.4),
),
ProductModel(
"titile3",
"name3",
"https://image.freepik.com/free-vector/people-using-online-apps-set_74855-4457.jpg",
Colors.yellow.withOpacity(0.4),
),
]
和main.dart 我跳过了第一个 flutter 的样板代码,只是复制了我关心的主要内容,
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
child: ListView.builder(
itemCount: modelProduct.length,
itemBuilder: (context, index) {
return createItem(context, index);
})),
);
}
}
Widget createItem(BuildContext context, index) {
return Container(
height: MediaQuery.of(context).size.height * 0.3,
width: MediaQuery.of(context).size.width,
child: Text(modelProduct[index].title),
color: Color(modelProduct[index].color),
);
}
问题出在color: Color(modelProduct[index].color)这一行 ,错误是
The argument type 'Color' can't be assigned to the parameter type 'int'.
但我知道,如果我在模型类中将颜色类型转换为 int ,并提供像 0xFFFFFF 这样的 int 类型颜色值,那么错误就会解决,但我的问题是我是否想使用像这样的 Material 颜色我上面用过,请问怎么用。 谢谢
最佳答案
可以直接使用color: modelProduct[index].color
代码片段
return Container(
height: MediaQuery.of(context).size.height * 0.3,
width: MediaQuery.of(context).size.width,
child: Text(modelProduct[index].title),
color: modelProduct[index].color,
);
关于flutter - 参数类型 'Color' 无法分配给参数类型 'int',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63333780/