I am developing a Flutter app using Provider (provider: 3.0.0+1). I am using MultiProvider using StreamProvider with controller. But I am always getting an error.
Below is my code
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();
}
}
But I Am always getting this error:
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)
Line: 20:80 in main.dart is (RecipeStreamService().controllerOut)
****** UPDATE ******
Changed Multiprovider to below code
providers: [
StreamProvider<List<Recipe>>.value(value: RecipeStreamService().controllerOut)
],
Also in HomePage.dart, where I use it, I have
final recipeService = Provider.of<List<Recipe>>(context);
Now, recipeService is always coming as null
Thanks
controllerOut
doesn't seem like it is a stream – WhereuntocontrollerOut.add
instead ofcontrollerIn.add
? dart.dev/articles/libraries/creating-streams – Diploma