flutter “TextStyle?”无法分配给参数类型“TextStyle”

6mw9ycah  于 11个月前  发布在  Flutter
关注(0)|答案(5)|浏览(132)

我得到这个空的安全错误,而我的Flutter应用程序的工作。

The argument type 'TextStyle?' can't be assigned to the parameter type 'TextStyle'.

下面是抛出此错误的代码段:

ButtonStyle(textStyle: MaterialStateProperty.all<TextStyle>(Theme.of(context).textTheme.button))

VS Code建议将not运算符放在参数的末尾。

ButtonStyle(textStyle: MaterialStateProperty.all<TextStyle>(Theme.of(context).textTheme.button!))

**问题:这是一个好的做法吗!**在我的代码中,在这种情况下还有什么其他解决方案?

bvjveswy

bvjveswy1#

如果为材质TextStyle导入了错误的库,也会出现此错误。
这可能发生在你使用:

import 'dart:ui';

而不是:

import 'package:flutter/material.dart';
rkkpypqq

rkkpypqq2#

MaterialStateTextStyle.resolveWith((states)=> TextStyle(fontSize:12),
可以使用. resolveWith 方法从MaterialPropertyResolver回调函数创建MaterialStateTextStyle。

li9yvcax

li9yvcax3#

材料状态属性表示依赖于小部件的材料“状态”的值。状态被编码为一组MaterialState值,如MaterialState.focused、MaterialState.hovered、MaterialState. pressed。overlayColor定义了在按下、聚焦或悬停时填充墨水池的颜色(“飞溅颜色”)。InkWell使用覆盖颜色的解析方法来计算墨水池当前状态的颜色。
你可以只使用上下文的主题来使用主题textStyle,像这样:

Text("copied text theme",
 textAlign: TextAlign.center,
 style: Theme.of(context).textTheme.button)
ia2d9nvy

ia2d9nvy4#

在Buildcontext中初始化样式,示例:

var _styleType = Theme.of(context)
                                .textTheme
                                .body1
                                .copyWith(color: Colors.white);

然后将其应用于Widget:

Container(
                        margin: EdgeInsets.symmetric(vertical: 10),
                        child: new Text("\u00a9 TasnuvaOshin",
                            overflow: TextOverflow.ellipsis,
                            style: _styleType),
                      ),
nx7onnlm

nx7onnlm5#

我知道这是2岁以上,但我认为真实的(编辑:更简单,因为以前的答案作品)答案仍然失踪。问题是,它正在寻找一个非空的TextTheme,而你正在提供一个可空的TextTheme。但是属性本身正在寻找可空的TextTheme。这是你的一行,使它寻找一个非空的TextTheme
所以在这一行:

ButtonStyle(textStyle: MaterialStateProperty.all<TextStyle>(Theme.of(context).textTheme.button))

此属性可以接受可空的TextStyle:
ButtonStyle(textStyle:
此表达式返回可为空的TextStyle
Theme.of(context).textTheme.button)
是你的类型声明说它不能为空:
MaterialStateProperty.all
你只需要加一个?你的类型:

MaterialStateProperty.all<TextStyle?>

相关问题