Flutter StreamProvider报错:StreamController非Stream类型问题解决
I was implementing a network connectivity status feature using Provider and Connectivity, following a tutorial. When setting up StreamProvider, I hit this error:
error: The return type 'StreamController
' isn't a 'Stream', as defined by anonymous closure.
Here's the problematic code from main.dart:
@override Widget build(BuildContext context) { return StreamProvider( builder: (context) => ConnectivityService().connectionStatusController, // ERROR LINE child: ChangeNotifierProvider<ThemeChanger>( builder: (_) => ThemeChanger((x) ? ThemeChanger.customDarkTheme : ThemeChanger.customLightTheme), child: new MaterialAppWithTheme(), ), ); }
I tried replacing my code with the version from the tutorial's repository and searching for fixes online, but nothing worked initially. I even suspected conflicts with other Provider usages might be causing the issue.
Eventually, I found the solution by adjusting the code to access the stream property of the StreamController:
@override Widget build(BuildContext context) { return StreamProvider( builder: (context) => ConnectivityService().connectionStatusController.stream, // Added the .stream suffix child: ChangeNotifierProvider<ThemeChanger>( builder: (_) => ThemeChanger((x) ? ThemeChanger.customDarkTheme : ThemeChanger.customLightTheme), child: new MaterialAppWithTheme(), ), ); }
The root cause appears to be a package update that happened after the tutorial was published. StreamProvider now expects a Stream instance directly, so you can't pass the StreamController itself—you need to explicitly reference its underlying .stream property instead.
内容的提问来源于stack exchange,提问作者princeoo7

