use*_*960 18 provider stream dart flutter flutter-provider
我正在使用 Provider(提供程序:3.0.0+1)开发 Flutter 应用程序。我正在使用带有控制器的 StreamProvider 的 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'),
),
);
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
但我总是收到此错误:
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)
Run Code Online (Sandbox Code Playgroud)
行:main.dart 中的 20:80 是 (RecipeStreamService().controllerOut)
****** 更新 ******
将 Multiprovider 更改为以下代码
providers: [
StreamProvider<List<Recipe>>.value(value: RecipeStreamService().controllerOut)
],
Run Code Online (Sandbox Code Playgroud)
同样在我使用它的 HomePage.dart 中,我有
final recipeService = Provider.of<List<Recipe>>(context);
Run Code Online (Sandbox Code Playgroud)
现在, recipeService 总是为空
谢谢
您看到错误的原因是您传递给as的类型参数与您返回的类型参数不匹配。StreamProvider<T>Tcreate
在这种情况下,您想要流式传输类型的值List<Recipe>。
因此,您还应该将其传递给泛型类型:
StreamProvider<List<Recipe>>.value(value: stream)
Run Code Online (Sandbox Code Playgroud)
哪里stream是你的List<Recipe>流。
如果为您Provider.of<List<Recipe>>(context)返回null,则表示您尚未向流添加值。
如果您想要null在流发出值之前有其他内容,您可以传递initialValue:
StreamProvider<List<Recipe>>.value(
value: stream,
initialValue: initialRecipes,
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6542 次 |
| 最近记录: |