在颤振应用程序中坚持与 sqflite 的提供商集成
Posted
技术标签:
【中文标题】在颤振应用程序中坚持与 sqflite 的提供商集成【英文标题】:Stuck with provider integration with sqflite in a flutter app 【发布时间】:2021-03-28 09:57:43 【问题描述】:我正在尝试实现提供程序模式,但我正在努力将其与 sqflite 数据库集成。 ChangeNotifier 类从数据库中获取字符串列表,然后将其与 ListView 一起显示。我想问题是当 ListView 构建小部件时,ChangeNotifier 类尚未初始化列表,因此应用程序崩溃。我该如何解决这个问题?
class FavouritesProvider with ChangeNotifier
List<String> _favourites;
List<String> get favourites => [..._favourites];
FavouritesProvider()
fetchAndSetFav();
Future<void> fetchAndSetFav() async
final data = await DBHelper.instance.getFavourites();
_favourites = data;
@override
Widget build(BuildContext context)
return Scaffold(
body: ChangeNotifierProvider(
create: (_) => FavouritesProvider(),
child: Container (
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: [
Colors.blue[200],
Colors.blue
],
stops: [0.0,1]
)
),
child: Consumer<FavouritesProvider>(
builder: (context, favouritesProvider, child) => ListView.builder (
itemCount: favouritesProvider.favourites.length,
itemBuilder: (context, index)
return Container(
padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
width: double.maxFinite,
child: FavouritePositionWidget(key: new Key(index.toString()), streetName: favouritesProvider.favourites[index])
);
,
)
)
)
)
);
但我得到了这个错误
The following NoSuchMethodError was thrown building Consumer<FavouritesProvider>(dirty, dependencies: [_InheritedProviderScope<FavouritesProvider>]):
The getter 'iterator' was called on null.
Receiver: null
Tried calling: iterator
【问题讨论】:
【参考方案1】:我认为问题在于您不能在同一个构建方法中同时创建和使用提供程序。一种常见的做法是在树的最顶端创建提供程序。
来自提供商example:
void main()
runApp(
/// Providers are above [MyApp] instead of inside it, so that tests
/// can use [MyApp] while mocking the providers
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => Counter()),
],
child: const MyApp(),
),
);
【讨论】:
以上是关于在颤振应用程序中坚持与 sqflite 的提供商集成的主要内容,如果未能解决你的问题,请参考以下文章