“文本样式?” 无法分配给参数类型“TextStyle”

Kas*_*lar 13 dart flutter

我在使用我的 flutter 应用程序时遇到此 null 安全错误。

The argument type 'TextStyle?' can't be assigned to the parameter type 'TextStyle'.
Run Code Online (Sandbox Code Playgroud)

这是引发此错误的代码片段:

The argument type 'TextStyle?' can't be assigned to the parameter type 'TextStyle'.
Run Code Online (Sandbox Code Playgroud)

VS Code 建议此解决方案将 not 运算符放在参数末尾。

ButtonStyle(textStyle: MaterialStateProperty.all<TextStyle>(Theme.of(context).textTheme.button!))
Run Code Online (Sandbox Code Playgroud)

问题:这是一个很好的做法吗?在我的代码中,在这种情况下还有哪些其他可能的解决方案?

小智 18

如果您为材质 TextStyle 导入了错误的库,您也可能会收到此错误。

当您使用以下方法时可能会发生这种情况:

import 'dart:ui';
Run Code Online (Sandbox Code Playgroud)

代替:

import 'package:flutter/material.dart';
Run Code Online (Sandbox Code Playgroud)


Ayy*_*air 1

材质状态属性表示取决于小部件的材质“状态”的值。状态被编码为一组 MaterialState 值,例如 MaterialState.focused、MaterialState.hovered、MaterialState.pressed。例如,InkWell.overlayColor 定义按下时(“初始颜色”)、聚焦或悬停时填充墨水的颜色。InkWell 使用叠加颜色的解析方法来计算墨水井当前状态的颜色。

您可以仅使用上下文主题来使用主题 textStyle,如下所示:

Text("copied text theme",
 textAlign: TextAlign.center,
 style: Theme.of(context).textTheme.button)
Run Code Online (Sandbox Code Playgroud)