繁体   English   中英

我正在尝试使用颤振制作 Bmi 计算器,但出现了很多错误

[英]I am trying to make the Bmi calculator using flutter but got many errors


import 'package:flutter/material.dart';

class ReusableCard extends StatelessWidget {
  ReusableCard({@required this.colour, this.cardChild, this.onPress}); // i am getting errors here
  final Color colour ;
  final Widget cardChild;
  final Function onPress;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onPress(),
      child: Container(
//if box decoration is there in the code then the color property should go in the box decoration property
        decoration: BoxDecoration(
            color:colour,
            borderRadius: BorderRadius.circular(15.0)
        ),
        margin: EdgeInsets.all(15.0),
      ),
    );
  }
}

我收到错误消息:参数“onPress”、“cardChild”、“color”因其类型而不能具有“null”值,但隐含的默认值为“null”。 在飞镖分析中

您面临的错误是由空安全引起的,您可能希望将类型从以下位置更改:

final Color colour ;
final Widget cardChild;
final Function onPress;

//to

final Color? colour ;
final Widget? cardChild;
final Function? onPress;

但是我建议您将它们全部放在带有装饰器@required的构造函数中

您可以在官方文档中了解有关空安全语法的更多信息:
https://flutter.dev/docs/null-safety

我遇到了同样的错误,即使使用@required装饰器也不足以解决问题,为我解决的问题是我必须禁用项目的空安全性,这是通过从 ">=降级颤振版本2.12.0 <3.0.0" 到 ">=2.11.0 <3.0.0" 通过修改pubspec.yaml文件。 特别是在依赖项-> sdk 下。

请记住,通过降级项目的颤振版本将禁用 null-safety 的整个使用,包括“?” 检查运算符

为了更好地理解 Dart 语言中的 null-safety 特性,请阅读 Flutter Docs 的精彩内容: https ://dart.dev/null-safety#enable-null-safety

这也是一篇很好的综合文章https://petercoding.com/flutter/2021/03/04/using-null-safety-in-dart/

我在 onPress 的构造函数中添加了“必需”。 但是,我不能直接将它分配给 onTap: GestureDetector 小部件的一部分。 所以我从一个与预期的 onTap 方法签名匹配的方法中调用它。 最后,这是对我有用的(不优雅的)解决方案:

class ReusableCard extends StatelessWidget {

ReusableCard({required this.colour, this.cardChild, required this.onPress});

final Color colour;
final Widget? cardChild;
final Function onPress;

void onPressAction() {
    onPress();
}

@override
Widget build(BuildContext context) {
    return GestureDetector(
    onTap: onPressAction,
    child: Container(
      child: cardChild,
      margin: EdgeInsets.all(15.0),
      decoration: BoxDecoration(
        color: colour,
        borderRadius: BorderRadius.circular(10.0)
      ),
    ),
  );
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM