【问题标题】:The argument type 'MapShapeSource?' can't be assigned to the parameter type 'MapShapeSource'参数类型“MapShapeSource?”无法分配给参数类型“MapShapeSource”
【发布时间】:2021-09-03 14:42:39
【问题描述】:

我正在尝试实现同步融合并使用颤振显示地图。而且我似乎从一开始就遇到了 nullcheck 问题(实际上是教程视频)。它的 [MapShapeLayer(source: _shapeSource)] 不起作用它说:

“参数类型'MapShapeSource?'不能分配给参数类型“MapShapeSource”。”

如您所见,我有一个 ?在 MapShapeSource 之后,但我如何尝试解决这个问题,它似乎不起作用,有什么想法吗?

class MyHomePage extends StatefulWidget {

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  MapShapeSource? _shapeSource;

  @override
  void initState() {
    _shapeSource = MapShapeSource.network(
        'http://www.json-generator.com/api/json/get/bVqXoJvfjC?indent=2');
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.fromLTRB(10, 50, 0, 0),
        child: SfMaps(
          layers: [MapShapeLayer(source: _shapeSource)],
        ),
      ),
    );
  }
}

【问题讨论】:

  • 尝试像late MapShapeSource _shapeSource;一样声明_shapeSource
  • 谢谢你。我必须阅读这个!

标签: flutter syncfusion


【解决方案1】:

您为不可为空的MapShapeLayer.source 属性使用了可空字段。您应该为此使用不可为空的字段。请查看此documentation 了解有关从网络加载 JSON 的信息。

【讨论】:

    【解决方案2】:

    错误

    该消息表明您的代码中某处正在使用可为空的 _shapeSource。虽然添加 late 修饰符是对编译器的承诺,您将负责并在使用之前将 _shapeSource 初始化为不可为空的值。 Dart 团队还建议您使用良好的编程习惯,以确保在使用该值之前处理可为空的情况。在这种情况下,如果您无法访问网络会发生什么情况(_shapeSource 会导致应用崩溃吗?)?

    这里有几个例子:

    在下面的情况下,可空参数奶制品在与替代品一起使用之前检查是否为空。

    // Using null safety:
    makeCoffee(String coffee, [String? dairy]) {
      if (dairy != null) {
        print('$coffee with $dairy');
      } else {
        print('Black $coffee');
      }
    }
    

    在下一种情况下,可空值在使用前被转换为不可空字符串。

    // Using null safety:
    requireStringNotObject(String definitelyString) {
      print(definitelyString.length);
    }
    
    main() {
      Object maybeString = 'it is';
      requireStringNotObject(maybeString as String);
    }
    

    建议

    在您的代码中,您可以创建一个备用小部件以在发生网络故障时显示,或者尝试转换该值,或在将值与三元运算符一起使用之前提供一个空检查(参见下面的示例)。这将是一个更好的做法,而不是单独添加后期修饰符。

    @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Padding(
            padding: EdgeInsets.fromLTRB(10, 50, 0, 0),
            child: SfMaps(
              layers: [MapShapeLayer(source: (_shapeSource != null) ? _shapeSource : _defaultNonNullSource)],
            ),
          ),
        );
      }
    

    您可以在 dart.dev 网站上阅读更多关于 null 安全性的内容,并且可以通过将代码粘贴到启用了 null 安全性的 dartpad.dev 来练习适用于您的代码的内容并查看建议。

    【讨论】:

      猜你喜欢
      • 2023-01-18
      • 2022-12-24
      • 2023-02-10
      • 2021-07-09
      • 2021-08-22
      • 2021-11-03
      • 1970-01-01
      • 2022-08-14
      • 2019-06-24
      相关资源
      最近更新 更多