【发布时间】:2021-11-15 14:45:57
【问题描述】:
我的目标是生成多个不同颜色的 Stickynote, 我已经建立了六种不同颜色的列表。 我想把它们洗牌。
错误
"message": "无法在初始化程序中访问实例成员 'color'。\n尝试用不同的表达式替换对实例成员的引用",
代码如下:
import 'dart:math';
import 'package:flutter/cupertino.dart';
class Sticky {
final String note;
List color = [
const Color(0xffB85252),
const Color(0xffB4C6A6),
const Color(0xffF4ABC4),
const Color(0xff346751),
const Color(0xffFFC947),
const Color(0xff3282B8),
];
var colorItem = (color.toList()..shuffle()).first;
Sticky({required this.note, required this.color});
}
class StickyNote extends StatefulWidget {
final color;
final String note;
const StickyNote({Key? key, this.color, required this.note})
: super(key: key);
@override
_StickyNoteState createState() => _StickyNoteState();
}
class _StickyNoteState extends State<StickyNote> {
@override
Widget build(BuildContext context) {
return Container(
width: 300,
height: 300,
color: Sticky.colorItem,
);
}
}
【问题讨论】:
-
为什么,你同时使用
required this.color和初始化? -
消息很清楚你没有初始化 Sticky 实例,在 statefull 中创建一个方法不是更好吗?
标签: flutter dart flutter-layout