我正在尝试用GetX做一个非常简单的页面路由,使用的是最新版本的Flutter,它包含了空安全性。即使我没有传递任何参数或引用任何变量,它也一直返回错误"Null check operator used on a null value“。
下面是我非常简单的代码:
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Flutter Demo',
home: MyHomePage(title: 'Flutter Demo Home Page'),
getPages: [GetPage(name: PageTwo.id, page: () => PageTwo())],
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _newPage() {
Get.toNamed(PageTwo.id);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
floatingActionButton: FloatingActionButton(
onPressed: _newPage,
tooltip: 'newPage',
child: Icon(Icons.add),
),
);
}
}
class PageTwo extends StatelessWidget {
static String id = 'page2';
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
child: Text('hi'),
);
}
}
正如您所看到的,没有理由选择任何空值。
我在我的pubspec.yaml文件中使用了以下包:
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
get: ^4.3.4
发布于 2021-08-09 04:46:11
在Flutter中使用命名路由时,最好始终在名称之前使用/
。所以对你来说就是
static const id = '/page2'; // const not part of the fix, but it can and should be const
这将消除null错误。
你也可以在没有命名路由的情况下导航,这个错误也不是问题。
Get.to(() => PageTwo());
https://stackoverflow.com/questions/68701556
复制相似问题