#flutter #dart
#flutter #dart
Вопрос:
Я попытался сделать это, чтобы все цвета оставались внутри класса Color, чтобы у них было пространство имен:
class Color {
const Color currentSection = const Color(0x626262);
const Color aBackground = const Color(0xE5E5E5);
const Color aSidebar = const Color(0x7C01FF);
const Color aSoundButton = const Color(0xA93EF0);
const Color aSoundLockedButton = const Color(0x555555);
const Color aSoundButtonText = const Color(0xFFFFFF);
}
но я получаю ошибки при const: Const variables must be initialized with a constant value.
Как я могу создать класс просто как контейнер?
Ответ №1:
Вы можете скопировать вставить выполнить полный код ниже
шага 1: Использовать static const
Шаг 2: Вы потеряли два символа, вы можете изменить 0x626262
на 0x62626200
, при использовании с Android Studio
, вы можете видеть цвет, если определение правильное
, вы также можете ссылаться на исходный код colors.dart
https://github.com/flutter/flutter/blob/d8167b90e26038b4290331e555211e781e0cddea/packages/flutter/lib/src/material/colors.dart#L198
фрагмент кода
class CustomColors {
static const Color currentSection = Color(0x62626200);
static const Color aBackground = Color(0xE5E5E500);
static const Color aSidebar = Color(0x7C01FF00);
static const Color aSoundButton = Color(0xA93EF000);
static const Color aSoundLockedButton = Color(0x55555500);
static const Color aSoundButtonText = Color(0xFFFFFF00);
}
рабочая демонстрация
полный код
import 'package:flutter/material.dart';
class CustomColors {
static const Color currentSection = Color(0x62626200);
static const Color aBackground = Color(0xE5E5E500);
static const Color aSidebar = Color(0x7C01FF00);
static const Color aSoundButton = Color(0xA93EF000);
static const Color aSoundLockedButton = Color(0x55555500);
static const Color aSoundButtonText = Color(0xFFFFFF00);
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter ;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(width: 100, height: 100,color: CustomColors.aSoundLockedButton),
Container(width: 100, height: 100, color: CustomColors.aSoundButton),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Ответ №2:
Измените имя вашего Color
класса на что-то вроде MyColor
. Вы пытаетесь создать объекты Dart / Flutter Color
, но вы создали конфликт имен. Он пытается создать объекты из вашего Color
класса, у которого нет постоянного конструктора, что вызывает ошибку. Кроме того, добавьте static
before const
для ваших объявлений.
Ответ №3:
class Colors {
static Color currentSection = Color(0xff626262);
static Color aBackground = Color(0xffE5E5E5);
static Color aSidebar = Color(0xff7C01FF);
static Color aSoundButton = Color(0xffA93EF0);
static Color aSoundLockedButton = Color(0xff555555);
static Color aSoundButtonText = Color(0xffFFFFFF);
}
попробуйте вот так.