延迟初始化错误:字段"过滤器值"尚未初始化



我对flutter很陌生,对编程也很陌生。我在尝试运行/调试应用程序时收到此错误消息。我们正在创建一个ToDoList作为一个学校项目,不知道该怎么办。任何帮助都将不胜感激!

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'EditTodoView.dart';
import 'TodoList.dart';
import 'model.dart';
class TodoListView extends StatefulWidget {
const TodoListView({Key? key}) : super(key: key);
@override
_TodoListViewState createState() => _TodoListViewState();
}
class _TodoListViewState extends State<TodoListView> {
final List<String> filteredAlternatives = ['All', 'Done', 'Undone'];
late String filterValue;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text(
"TIG169 TODO",
style: TextStyle(color: Colors.black),
),
actions: <Widget>[
_todoFilter(),
],
),
body: Consumer<MyState>(
builder: (context, state, child) => TodoList(state.filter(filterValue)),
),
floatingActionButton: _addTodoButton(context),
);
}
Widget _todoFilter() {
return PopupMenuButton<String>(
onSelected: (String value) {
setState(() {
filterValue = value;
});
},
itemBuilder: (BuildContext context) {
return filteredAlternatives
.map((filterAlternatives) => PopupMenuItem(
value: filterAlternatives, child: Text(filterAlternatives)))
.toList();
},
icon: const Icon(Icons.more_vert, size: 20, color: Colors.black),
);
}
Widget _addTodoButton(BuildContext context) {
return FloatingActionButton(
backgroundColor: (Colors.grey),
child: const Icon(Icons.add),
onPressed: () async {
var newTodo = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EditTodoView(
Todo(
todoText: '',
),
)),
);
if (newTodo != null) {
Provider.of<MyState>(context, listen: false).addTodo(newTodo);
}
});
}
void whenComplete(Null Function() param0) {}
}

当我尝试调试它时,我收到的错误消息是:

Exception caught by widgets library 
The following LateError was thrown building Consumer<MyState>(dirty, dependencies: [_InheritedProviderScope<MyState?>]):
LateInitializationError: Field 'filterValue' has not been initialized.
The relevant error-causing widget was
Consumer<MyState>
package:firstapp/TodoListView.dart:32"

late字符串filterValue;

此语句给您带来了问题,因为它后面跟有late关键字。Late关键字允许您初始化一个变量";第一次读取它时;而不是它的创造。

您应该能够通过给它一个默认值并删除late关键字来解决这个问题。像这样:

String filterValue = ""; (giving it a default value)

或者您可以通过添加一个来使它可以为null在数据类型之后。但是要小心,因为如果不小心处理,您可能会通过将其设为null来遇到"called on null">错误。像这样:

String? filterValue; (making it nullable)

这样,变量将在编译时而不是运行时创建,并且LateInitializationError应消失。

您的问题是试图使用filterValue,当调用它时,它还没有值。CCD_ 2关键字类似于";hack";。它告诉程序:;如果filterValue现在没有值,不用担心,使用时会有&";。

因此,作为解决方案,我认为要么将默认值设置为filterValue并删除late关键字,要么确保filterValue在使用之前有一个值。

相关内容

最新更新