【问题标题】:Non-nullable instance field 'categoryTitle' must be initialized. Try adding an initializer expression or a generative constructor that initializes it必须初始化不可为空的实例字段“categoryTitle”。尝试添加初始化表达式或生成构造函数来初始化它
【发布时间】:2021-12-15 20:16:51
【问题描述】:

我不明白如何解决此错误,因为如果我将其标记为延迟,则会引发异常并且该字段尚未初始化。我是新来的,所以如果有人可以提供帮助,那就太好了。我试图在页面弹出时删除带有 id 的项目。我将无状态小部件转换为有状态小部件。我正在听一个讲座并做了同样的事情,但它对我不起作用。

  class CategoryMealScreen extends StatefulWidget {
  static const routeName = '/categories -meals';

  @override
  State<CategoryMealScreen> createState() => _CategoryMealScreenState();
}

class _CategoryMealScreenState extends State<CategoryMealScreen> {
  String categoryTitle ;
  late List<Meal> displayedMeals;
  bool _loadedInitData = false;

  @override
  void initState() {
    super.initState(); 
  }

  @override
  void didChangeDependencies() {
    if (_loadedInitData == false) {
      final routeArgs = ModalRoute.of(context)!.settings.arguments as Map<
          String, String>; 
      final categoryTitle = routeArgs['title'] as String;
      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,
            complexity: displayedMeals[index].complexity,
            duration: displayedMeals[index].duration,
            imageUrl: displayedMeals[index].imageUrl,
            affordability: displayedMeals[index].affordability,
            removeItem: _removeMeal,
          );
        },
        itemCount: displayedMeals.length,
      ),
    );
  }
}

【问题讨论】:

  • String? categoryTitle ;String categoryTitle = ''; 的方式初始化您的 categoryTile 变量

标签: flutter flutter-layout flutter-dependencies flutter-web


【解决方案1】:

尝试替换:

late List<Meal> displayedMeals;

List?<Meal> displayedMeals;

【讨论】:

    猜你喜欢
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 2023-01-02
    • 2022-01-25
    • 2021-07-06
    • 1970-01-01
    • 2023-01-05
    • 2021-09-14
    相关资源
    最近更新 更多