我刚刚开始使用flutter进行编码,并使用文本小部件解决了此问题,它在应用程序的第二页上引发了“断言失败:第241行pos 10:'data!= null'”
我尝试将“ list.title”更改为“ hello”,但是它不起作用,而且如果我在首页中使用文本小部件,效果很好
// go to second page code
viewTodoList(BuildContext context,TodoList item){
assert(item!=null);
Navigator.pushNamed(context,TodoListView.routeName,arguments: item);
}
// second page code
class TodoListView extends StatefulWidget {
static const routeName ="/todo_list_view";
TodoListView({Key key, this.title}) : super(key: key);
final String title;
@override
_TodoListViewState createState() => _TodoListViewState();
}
class _TodoListViewState extends State<TodoListView> {
final TodoList list=ModalRoute.of().settings.arguments;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),//appBar
body: Text(list.title),
);//Scaffold
}
}
答案 0 :(得分:0)
如果您输入的是var
空值,请提供默认值
答案 1 :(得分:0)
将body: Text(list.title)
更改为Text("${list.title}")
诸如widget.title之类的东西也一样,
答案 2 :(得分:0)
您的page2构造函数需要一个标题:
TodoListView({Key key, this.title}) : super(key: key);
但是调用页面时您没有通过它:
Navigator.pushNamed(context,TodoListView.routeName,arguments: item);
如果未通过,则为null
(这是您的问题)。
您在配置命名路由时将其冷传递:
MaterialApp(
...
routes: [
TodoListView.routeName: (BuildContext context) => TodoListView(title:'Page 2'),
]
...
)
但是,如果要修复它,则应将其放在TodoListView中。
空安全示例:
Scaffold(
appBar: AppBar(
title: Text('Page 2'),
),//appBar
body: Text(list?.title ?? ''),
);//Scaffold
答案 3 :(得分:0)
// go to second page code
viewTodoList(BuildContext context,TodoList item){
assert(item!=null);
Navigator.pushNamed(context,TodoListView.routeName,arguments: item);
}
// second page code
class TodoListView extends StatefulWidget {
static const routeName ="/todo_list_view";
TodoListView({Key key, this.title}) : super(key: key);
final String title;
@override
_TodoListViewState createState() => _TodoListViewState();
}
class _TodoListViewState extends State<TodoListView> {
final TodoList list=ModalRoute.of().settings.arguments;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title ?? ""),
),//appBar
body: Text(list.title ?? ""),
);//Scaffold
}