【发布时间】:2021-07-06 06:01:02
【问题描述】:
我在 main.dart 中使用 SQflite 从本地数据库中获取数据,并使用 FutureProvider 将其传递给 ProvideRecords 小部件:
Future<List<WeightRecord>> _getRecords() async {
List<WeightRecord> records = await RecordsDatabase.instance.getRecords();
return records;
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: FutureProvider<List<WeightRecord>?>(
create: (context) {
return _getRecords();
},
initialData: [],
catchError: (_, error) => [
WeightRecord(
date: DateTime.now(), weight: 00.0, note: 'hasError: $error')
],
child: ProvideRecords(),
),
);
}
}
然后在 ProvideRecords 小部件中,我再次将数据传递给另一个提供者:
class ProvideRecords extends StatelessWidget {
const ProvideRecords({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Consumer<List<WeightRecord>?>(builder: (context, list, child) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => RecordsListModel()),
ChangeNotifierProvider(create: (context) => ButtonMode())
],
builder: (context, child) {
Provider.of<RecordsListModel>(context, listen: true)
.updateRecordsList(list);
return Home(list: list);
});
}
});
}
}
代码有效,但我得到了setState() or markNeedsBuild() called during build.,因为我在构建器函数中使用了Provider.of<RecordsListModel>(context, listen: true).updateRecordsList(list);。但是我找不到另一种将数据从 FutureProvider 传递到 RecordListModel 的方法,我该怎么办?
【问题讨论】:
标签: flutter dart flutter-provider