Home > OS >  How to declare String and List in the current version of flutter?
How to declare String and List in the current version of flutter?

Time:01-31

In the tutorial, String categoryTitle; and List displayedMeals; were working fine. In the current version of flutter it won't allow me to just declare as it is. What should I initialize them to? It would be nice to know what is the equivalent in declaring String and List now since thre is a null safety. Also, when I put String? and ListMeal? as declaration and put [!], i get an error of null check operator used on a null value. I can't put late also because I don't what should I initialize these declarations.

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,
      ),
    );
  }
}

CodePudding user response:

It happens because of null safety. Either you declare your variables as nullable, so they can be null or you use the keyword late in front of the variable like this:

late String categoryTitle;
late List<Meal> displayedMeals;

But then you should also declare the variables in the initState or before you use them, otherwise an exception will be thrown.

CodePudding user response:

Write like that : String? categoryTitle; its nullsafety

  • Related