【问题标题】:Error The argument type 'Object?' can't be assigned to the parameter type 'Color?'错误参数类型“对象?”不能分配给参数类型“颜色?”
【发布时间】:2023-04-09 16:47:02
【问题描述】:

有我的代码: StreamBuilder 有错误

错误参数类型“对象?”不能分配给参数 输入'颜色?

body: Center(
          child: StreamBuilder(
            stream: bloc.stateStream,
            initialData: Colors.amber,
            builder: (context, snapshot) {
              return AnimatedContainer(
                duration: Duration(milliseconds: 500),
                width: 100,
                height: 100,
                color: snapshot.data,
              );
            },
          ),
        ),
        body: Center(
          child: StreamBuilder(
            stream: bloc.stateStream,
            initialData: Colors.amber,
            builder: (context, snapshot) {
              return AnimatedContainer(
                duration: Duration(milliseconds: 500),
                width: 100,
                height: 100,
                color: snapshot.data,
              );
            },
          ),
        ),
      ),
    );
  },
}

【问题讨论】:

  • 您正在将类型 Object 分配给颜色属性,颜色属性需要颜色类型的值。你的 stateStream 是否返回颜色?
  • 是的,我要返回颜色
  • 你能用 BLoC 更新你的代码吗?
  • 您可以格式化代码以获得更好的可读性。
  • 不要直接传递:color:snapshot.data,而是在return语句前使用color的变量,然后在color属性中使用。

标签: flutter


【解决方案1】:

您收到错误是因为snapshot 的类型为AsyncSnapshot<Object?>,并且当您将颜色设置为snapshot.dataObject 类型)时,类型不匹配,因为颜色应为Color 类型。

您可以通过指定 StreamBuilder 使用的流类型来修复错误,如下所示:

    body: Center(
              child: StreamBuilder<Color>( //Add <Color> after StreamBuilder
                stream: bloc.stateStream,
                initialData: Colors.amber,
                builder: (context, snapshot) {
                  return AnimatedContainer(
                    duration: Duration(milliseconds: 500),
                    width: 100,
                    height: 100,
                    color: snapshot.data,
                  );
                },
              ),
    ),

【讨论】:

    猜你喜欢
    • 2021-08-18
    • 2021-08-15
    • 2021-12-14
    • 2020-11-29
    • 2021-08-27
    • 2021-06-05
    • 2022-01-16
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多