Flutter 类型为'的值;主题数据';can';无法从方法'返回;构建';因为它的返回类型为';小部件';
我有如下代码Flutter 类型为'的值;主题数据';can';无法从方法'返回;构建';因为它的返回类型为';小部件';,flutter,dart,Flutter,Dart,我有如下代码 import 'package:flutter/material.dart'; class MyAppTheme extends StatelessWidget { @override Widget build(BuildContext context) { return ThemeData(primaryColor: Colors.yellow); } } 我得到这个错误 无法从方法“build”返回类型为“ThemeData”的值,因为它的返回类型
import 'package:flutter/material.dart';
class MyAppTheme extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ThemeData(primaryColor: Colors.yellow);
}
}
我得到这个错误
无法从方法“build”返回类型为“ThemeData”的值,因为它的返回类型为“Widget”
我已经尝试了一段时间,比如更改构建
的返回
类型,并将其置于另一种类型,例如动态
,但它不能像它只期望的那样工作小部件
那么,如果我想将我的
主题数据
拆分到另一个文件,我该怎么办?有什么想法吗?非常欢迎您发布自己的解决方案您无法返回主题数据,因为它不是小部件,所以无法在屏幕上呈现,这就是为什么Flatter会给您这个错误。像这样使用主题数据
MaterialApp(
title: title,
theme: ThemeData(
// Define the default brightness and colors.
brightness: Brightness.dark,
primaryColor: Colors.lightBlue[800],
accentColor: Colors.cyan[600],
// Define the default font family.
fontFamily: 'Georgia',
// Define the default TextTheme. Use this to specify the default
// text styling for headlines, titles, bodies of text, and more.
textTheme: TextTheme(
headline1: TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold),
headline6: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
bodyText2: TextStyle(fontSize: 14.0, fontFamily: 'Hind'),
),
)
);
正如您正确判断的那样,
主题数据
根本不是一个小部件
。如果您试图创建主题数据
以插入MaterialApp
或类似文件的主题
参数,您只需创建一个顶级变量:
final myAppTheme = ThemeData(primaryColor: Colors.yellow);
// somewhere else
return MaterialApp(
theme: myAppTheme,
// ...
);