我對顫振很陌生,對一般的編程也很陌生。當我嘗試運行/除錯我的應用程式時,我收到此錯誤訊息。我們正在創建一個 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"
uj5u.com熱心網友回復:
后期字串過濾器值;
此陳述句給您帶來了問題,因為它后跟了late關鍵字。Late 關鍵字允許您在“第一次讀取時”而不是在創建時初始化變數。
您應該能夠通過為其提供默認值并洗掉后期關鍵字來解決此問題。像這樣:
String filterValue = ""; (giving it a default value)
或者您可以通過添加? 在資料型別之后。但要小心,因為如果處理不當,您可能會遇到“呼叫空值”錯誤,使其可空。像這樣:
String? filterValue; (making it nullable)
這樣,變數將在編譯時而不是運行時創建,并且LateInitializationError應該消失。
uj5u.com熱心網友回復:
你的問題是你試圖使用filterValue它,當被呼叫時,還沒有價值。late關鍵字就像一個“黑客”。它告訴程式:“不要擔心 filterValue 現在沒有值,它會在使用時有值!”。
因此,作為解決方案,我會說要么設定默認值filterValue并洗掉late關鍵字,要么確保filterValue在使用之前有一個值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/360809.html
上一篇:Flutterflutter_webview_plugin錯誤[NSNull長度]:無法識別的選擇器發送到ios上的實體
