#dart
#dart
Вопрос:
Я пытаюсь написать класс в dart, который будет генерировать виджет box при инициализации. Я пытаюсь передать цвет в конструкторе и использовать его внутри виджета SizedBox. Но я получаю сообщение об ошибке «Невозможно получить доступ к элементу экземпляра ‘color’ в инициализаторе».
class GenerateBox{
final int id;
final Color color;
final bool safe;
final bool home;
final String startpoint;
GenerateBox(this.id, this.safe, this.home, this.startpoint, this.color);
Widget Box = SizedBox(
height:100,
width:100,
child: DecoratedBox(
decoration: const BoxDecoration(
color: color,
),
)
);
}
Ответ №1:
вам нужен метод сборки:
class GenerateBox extends StatelessWidget{
final int id;
final Color color;
final bool safe;
final bool home;
final String startpoint;
GenerateBox(this.id, this.safe, this.home, this.startpoint, this.color);
@override
Widget build(BuildContext context) {
return SizedBox(
height:100,
width:100,
child: DecoratedBox(
decoration: const BoxDecoration(
color: color,
),
)
);
}
}
В качестве альтернативы вы можете использовать статический метод, как показано ниже:
class GenerateBox{
static SizedBox showSizedBox(
BuildContext context, {
final int id;
Color color;
bool safe;
bool home;
String startpoint;
}){
return SizedBox(
height:100,
width:100,
child: DecoratedBox(
decoration: const BoxDecoration(
color: color,
),
)
);
}
}
вы можете вызвать выше, как это:
назовите это так:
верните GenerateBox.showSizedBox(контекст,
цвет: color, безопасный: safe, home: home, начальная точка: начальная точка);