0

想要对 Card 使用强调色,并且由于不推荐使用强调色,所以我使用 colorScheme 代替 .Described colorScheme 在 MaterialApp 的 themeData 中。但最终无法将其用于卡。显示错误:“参数类型 'ColorScheme' 不能分配给参数类型 'Color'”

这是 MaterialApp 的主题数据

theme: ThemeData(
    primarySwatch: Colors.green,
    colorScheme: ColorScheme.fromSwatch().copyWith(secondary: Colors.red),
    canvasColor: Color.fromRGBO(255, 245, 224, 1),
    fontFamily: 'Raleway',
    textTheme: ThemeData.light().textTheme.copyWith(
          bodyText1: TextStyle(
            color: Color.fromRGBO(23, 45, 23, 1),
          ),
          bodyText2: TextStyle(
            color: Color.fromRGBO(23, 45, 23, 1),
          ),
          headline6: TextStyle(
            fontSize: 20,
            fontFamily: 'RobotoCondensed',
            fontWeight: FontWeight.bold,
          ),
        ),
  ),

这是使用它的卡

 Card(
      child: Text(selectedMeal.ingredients[i]),
      color: Theme.of(context).colorScheme,//error shows here
    ),
4

1 回答 1

1

colorScheme属性是ColorScheme类型,而color需要Color类型。

ColorScheme保存可以访问的不同颜色,例如,如下所示:

color: Theme.of(context).colorScheme.secondary,

下面是一个完整的例子:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
        colorScheme: ColorScheme.fromSwatch().copyWith(secondary: Colors.red),
        canvasColor: const Color.fromRGBO(255, 245, 224, 1),
        fontFamily: 'Raleway',
        textTheme: ThemeData.light().textTheme.copyWith(
              bodyText1: const TextStyle(
                color: Color.fromRGBO(23, 45, 23, 1),
              ),
              bodyText2: const TextStyle(
                color: Color.fromRGBO(23, 45, 23, 1),
              ),
              headline6: const TextStyle(
                fontSize: 20,
                fontFamily: 'RobotoCondensed',
                fontWeight: FontWeight.bold,
              ),
            ),
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Card(
          //child: Text(selectedMeal.ingredients[i]),
          color: Theme.of(context).colorScheme.secondary,
        ),
      ),
    );
  }
}
于 2021-10-30T12:34:18.267 回答