[英]How to declare String and List in the current version of flutter?
在教程中,String categoryTitle; 列出顯示的餐點; 工作正常。 在 flutter 的當前版本中,它不允許我按原樣聲明。 我應該將它們初始化為什么? 很高興知道現在聲明 String 和 List 的等價物是什么,因為存在 null 安全性。 另外,當我把字符串? 和 ListMeal? 作為聲明並放置 [,]。 我收到錯誤 null 檢查運算符用於 null 值。 我也不能遲到,因為我不知道我應該初始化這些聲明。
import 'package:flutter/material.dart';
import '../widgets/meal_item.dart';
import '../dummy_data.dart';
import '../models/meal.dart';
class CategoryMealsScreen extends StatefulWidget {
static const routeName = '/category-meals';
@override
State<CategoryMealsScreen> createState() => _CategoryMealsScreenState();
}
class _CategoryMealsScreenState extends State<CategoryMealsScreen> {
// final String categoryId;
String categoryTitle;
List<Meal> displayedMeals;
var _loadedInitData = false;
@override
void initState() {
super.initState();
}
@override
void didChangeDependecies() {
if (!_loadedInitData) {
final routeArgs =
ModalRoute.of(context)!.settings.arguments as Map<String, String>;
categoryTitle = routeArgs['title']!;
final categoryId = routeArgs['id'];
displayedMeals = DUMMY_MEALS.where((meal) {
return meal.categories.contains(categoryId);
}).toList();
}
_loadedInitData = true;
super.didChangeDependencies();
}
void _removeMeal(String mealId) {
setState(() {
displayedMeals!.removeWhere((meal) => meal.id == mealId);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(categoryTitle!),
),
body: ListView.builder(
itemBuilder: (ctx, index) {
return MealItem(
id: displayedMeals[index].id,
title: displayedMeals[index].title,
imageUrl: displayedMeals[index].imageUrl,
duration: displayedMeals[index].duration,
affordability: displayedMeals[index].affordability,
complexity: displayedMeals[index].complexity,
removedItem: _removeMeal,
);
},
itemCount: displayedMeals.length,
),
);
}
}
它發生是因為 null 安全。 要么將變量聲明為可為空,這樣它們就可以是 null,要么像這樣在變量前面使用關鍵字 late:
late String categoryTitle;
late List<Meal> displayedMeals;
但是你也應該在 initState 中或在使用它們之前聲明變量,否則會拋出異常。
這樣寫: String? categoryTitle;
String? categoryTitle;
它的空安全
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.