flutter - 参数类型 'Color' 无法分配给参数类型 'int'

标签 flutter dart

我是 dart 编程新手。 我发现了一个关于我的问题的错误,即“我创建了一个模型类和一个列表,模型类有一个 Color 类型的成员,然后在 ma​​in.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),
),
]

ma​​in.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/

相关文章:

flutter - 如何用新项目复制我自己创建的 flutter 项目

flutter - 在 flutter Dart 中创建和使用单例

android - 在 Flutter 中使用延迟重绘小部件

flutter - 如何在Flutter中关闭警报对话框?

Flutter 行文本溢出

google-maps - 获取数据快照到位置纬度经度

dart - Flutter - 如何将图像与渐变颜色混合?

json - Flutter不读取Json矩阵的名称

dart - 如何使用 Dart 在 angular2 中绑定(bind) ngFormModel?

flutter - 对两个文本小部件仅使用一次“对齐”