我正在使用提供程序(提供者:3.0.0 + 1)开发Flutter应用。我正在将MultiProvider与控制器一起使用。但是我总是遇到错误。
下面是我的代码
main.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);
现在,配方服务总是以空值出现
谢谢
答案 0 :(得分:0)
看到错误的原因是,由于StreamProvider<T>
传递给T
的 type参数与您返回{{ 1}} 。
在这种情况下,您要流式传输create
类型的值。
因此,您还应该将其传递给通用类型:
List<Recipe>
StreamProvider<List<Recipe>>.value(value: stream)
是您的stream
流。
如果List<Recipe>
为您返回Provider.of<List<Recipe>>(context)
,则表示您尚未向流中添加值。
如果要在流发出值之前使用null
以外的其他内容,则可以传递null
:
initialValue