无法将参数类型“颜色”分配给参数类型“ int”

时间:2020-08-10 03:36:06

标签: flutter dart

我是飞镖编程新手。 我发现了关于我的问题的错误,这是关于“我创建了一个模型类和一个列表,该模型类的成员类型为 Color ,然后在 main.dart 中,我想在 ListView.builder 中显示我的模型数据的列表,但是当在单独的容器小部件中时,其他所有功能都工作正常,但是color属性给出了错误,我尝试更改类型索引参数,但错误仍然存​​在。“

这是代码:

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 我跳过了第一个颤动的样板代码,只是复制了我最关心的事情,

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(modelProduct [index] .color) ,错误是

The argument type 'Color' can't be assigned to the parameter type 'int'.

但是我知道如果我在模型类中将颜色类型转换为int并提供像0xFFFFFF这样的color的int类型值,那么错误就可以解决,但是我的问题是我是否想使用像我在上面用过,怎么做。 谢谢

3 个答案:

答案 0 :(得分:2)

您可以直接使用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,
);

答案 1 :(得分:0)

尝试以下代码:

Container( 
  height: MediaQuery.of(context).size.height* 0.3,
  width: MediaQuery.of(context).size.width,
   child: Text(modelProduct[index].title),
   color: modelProduct[index].color
   );

答案 2 :(得分:0)

以下对我有用

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.value,
);

它需要颜色的 int 值