Flutter:入门常见报错整理以及常见示例整理

2023-07-30  本文已影响0人  xing_x
1.报错问题

Invalid constant value.dart(invalid_constant)
代码如下:

Widget _buildView() {
    return const Center(
      child: ElevatedButton(
        child: Text("normal"),
        onPressed: () {},
      ),
    );
  }

很简单的一个视图代码报错,提示无效的声明,vscode也无法自动修复,仔细看报错信息invalid_constant,也就是center声明const无效,删掉const就ok了。
const的意义:
1.const在某些场景可以节约内存,加速页面rebuild时间。
2.final可以理解为"不那么严格的const"。

2.flutter通过getx传值model

报错信息1:
LateError (LateInitializationError: Field 'currentModel' has not been initialized.)
代码如下:

  //传值对象
  var lastObject;
  late StudentModel currentModel;
  // = StudentModel('', '', '', '');
  var name;
  _initData() {
    update(["detialpage"]);

    // ignore: prefer_interpolation_to_compose_strings
    // Log.i('导航传值--->' + Get.arguments);
    lastObject = Get.arguments as Map;
    // ignore: prefer_interpolation_to_compose_strings
    Log.i('导航传值--->' + lastObject['title'].toString());

    name = lastObject['title'].toString();
    currentModel = lastObject['model'];
  }

根据字面意思来理解是currentModel没有被初始化,解决办法就是初始化currentModel,(StudentModel是自定义的一个model类)

late StudentModel currentModel =  StudentModel('', '', '', '');

在需要使用的地方就可以直接调用model显示内容

class _DetialpageViewGetX extends GetView<DetialpageController> {
  _DetialpageViewGetX({Key? key}) : super(key: key);
  //实例化控制器
  DetialpageController vc = Get.put(DetialpageController());
  // 主视图
  Widget _buildView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(vc.name.toString()),
          Text(vc.currentModel.name),
        ],
      ),
    );
  }

传值的方法

StudentModel model = StudentModel('zzilx', '18.0', '小学', 'Flutter');

//别名方式跳转
Get.toNamed(RouteNames.detail,
          arguments: {'title': 'flutter入门', 'model': model});

3.flutter通过getx传值int类型的值
_TypeError (type 'Null' is not a subtype of type 'int')

_TypeError (type 'String' is not a subtype of type 'int' of 'index')

上一篇 下一篇

猜你喜欢

热点阅读