簡體   English   中英

在 Flutter 中訪問 Widgets 中的 colorScheme

[英]Accessing colorScheme in Widgets in Flutter

想對 Card 使用強調色,因為不推薦使用強調色,所以我使用 colorScheme 代替。在 MaterialApp 的 themeData 中描述了 colorScheme。 但最終不能用於卡。 顯示錯誤:“無法將參數類型‘ColorScheme’分配給參數類型‘Color’”

這是來自 MaterialApp 的 themeData

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
    ),

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,
        ),
      ),
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM