我正在使用 Provider (provider: 3.0.0+1) 开发一个 Flutter 应用程序。我正在使用带有控制器的 StreamProvider 的 MultiProvider。但我总是遇到错误。
下面是我的代码
主要.dart
Widget build(BuildContext context) {
return MultiProvider(
providers: [
StreamProvider<RecipeStreamService>.value(value: RecipeStreamService().controllerOut)
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Home Food',
routes: {
'/register': (BuildContext context) => RegisterPage(),
'/login': (BuildContext context) => LoginPage()
},
theme: ThemeData(
primaryColor: Colors.lightBlue[300],
accentColor: Colors.green[300],
textTheme: TextTheme(
headline: TextStyle(fontSize: 42.0, fontWeight: FontWeight.bold, color: Colors.black54),
title: TextStyle(fontSize: 22.0, fontStyle: FontStyle.italic),
body1: TextStyle(fontSize: 18.0),
button: TextStyle(fontSize: 20.0,fontWeight: FontWeight.normal, color: Colors.white)
)
),
home: HomePage(title: 'Home'),
),
);
}
RecipeStreamService.dart
class RecipeStreamService {
List<Recipe> _recipes = <Recipe>[];
final _controller = StreamController<List<Recipe>>.broadcast();
get controllerOut => _controller.stream;
get controllerIn => _controller.sink;
RecipeStreamService() {
getRecipes();
}
addNewRecipe(Recipe recipe) {
_recipes.add(recipe);
controllerIn.add(_recipes);
}
getRecipes() async{
List<Map<String, dynamic>> result = await ApiService().getRecipes();
List<Recipe> data = result.map((data) => Recipe.fromMap(data)).toList();
data.map((f) => addNewRecipe(f));
}
void dispose() {
_controller.close();
}
}
但我总是收到这个错误:
type '_BroadcastStream<List<Recipe>>' is not a subtype of type 'Stream<RecipeStreamService>'
I/flutter (16880): When the exception was thrown, this was the stack:
I/flutter (16880): #0 MyApp.build (package:app_recipe/main.dart:20:80)
行:main.dart 中的 20:80 是 (RecipeStreamService().controllerOut)
****** 更新 ******
将 Multiprovider 更改为以下代码
providers: [
StreamProvider<List<Recipe>>.value(value: RecipeStreamService().controllerOut)
],
同样在我使用它的 HomePage.dart 中,我有
final recipeService = Provider.of<List<Recipe>>(context);
现在,recipeService 总是以 null 的形式出现
谢谢