18

我正在使用 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 的形式出现

谢谢

4

1 回答 1

1

您看到错误的原因是您传递给as的类型参数与您返回的参数不匹配。StreamProvider<T>Tcreate

在这种情况下,您希望流式传输type 的值List<Recipe>
因此,您还应该将其传递给泛型类型:

StreamProvider<List<Recipe>>.value(value: stream)

stream你的List<Recipe>流在哪里。


如果为您Provider.of<List<Recipe>>(context)返回null,则表示您尚未向流中添加值。

如果您想null在流发出值之前拥有其他东西,您可以通过initialValue

StreamProvider<List<Recipe>>.value(
  value: stream,
  initialValue: initialRecipes,
)
于 2020-11-28T20:05:10.497 回答