我正在構建一個食物食譜應用程式,用戶可以在其中瀏覽各種食譜。功能是,當用戶點擊洗掉按鈕時,該專案將不會顯示在串列中。我導航mealId到上一個螢屏,即串列螢屏通過
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context).pop(mealId);
},
child: const Icon(Icons.delete),
),
我在向后小部件中收到 pop() 值,例如:
void selectMeal(BuildContext context) {
Navigator.of(context)
.pushNamed(MealsDetailsScreen.routeName, arguments: id)
.then((result) {
if (result != null) {
removeItem(result);
print(result); // it prints the expected id
}
});
}
在完全附加的代碼中,我想通過以下方式洗掉專案詳細資訊 mealId
void _removeMeal(String mealId) {
setState(() {
print("$mealId from didChangedDependancies"); //it also prints the expected id
displayedMeals.removeWhere((meal) => meal.id == mealId);
});
}
我將函式設定為洗掉的代碼:
import 'package:flutter/material.dart';
import '../models/meals.dart';
import '../models/dummy_data.dart';
import '../widgets/meal_item.dart';
class CategoryMealaScreen extends StatefulWidget {
static const routeName = '/category-meals';
@override
State<CategoryMealaScreen> createState() => _CategoryMealaScreenState();
}
class _CategoryMealaScreenState extends State<CategoryMealaScreen> {
late String categoryTitle;
late List<Meal> displayedMeals;
var _loadedInitData = false;
@override
void initState() {
super.initState();
}
@override
void didChangeDependencies() {
if (!_loadedInitData) {
final routeArgs =
ModalRoute.of(context)!.settings.arguments as Map<String, String>;
categoryTitle = routeArgs['title'].toString();
final categoryId = routeArgs['id'];
displayedMeals = dummyMeals.where((meal) {
return meal.categories.contains(categoryId);
}).toList();
_loadedInitData = true;
}
super.didChangeDependencies();
}
void _removeMeal(String mealId) {
setState(() {
print("$mealId from didChangedDependancies");
displayedMeals.removeWhere((meal) => meal.id == mealId);
});
}
@override
Widget build(BuildContext context) {
final routeArgs = // received data from widget CategoryItems()
ModalRoute.of(context)!.settings.arguments as Map<String, String>;
final categoryTitle = routeArgs['title'];
final categoryId = routeArgs['id'];
final displayedMeals = dummyMeals.where((meal) {
return meal.categories.contains(categoryId);
}).toList();
return Scaffold(
appBar: AppBar(
title: Text(categoryTitle.toString()),
),
body: ListView.builder(
itemCount: displayedMeals.length,
itemBuilder: (ctx, index) {
return MealItem(
id: displayedMeals[index].id,
title: displayedMeals[index].title,
imageUrl: displayedMeals[index].imageUrl,
complexity: displayedMeals[index].complexity,
affordability: displayedMeals[index].affordability,
duration: displayedMeals[index].duration,
removeItem: _removeMeal,
);
}),
);
}
}
控制臺上沒有顯示錯誤。如果你們幫幫我,我會很高興的!非常感謝??
uj5u.com熱心網友回復:
final displayedMeals在您的build方法中洗掉。
改用方法displayedMeals之外的變數build。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/369378.html
