我会尽量简短,只添加相关的代码片段。 这是尝试从 JSON 加载 Item 对象的屏幕:
Widget _buildItemList(List<Item> currentItemList) {
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: currentItemList.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) {
return ItemDetailsPage(
item: currentItemList[index]);
},
));
},
child: Text(currentItemList[index].productName)
);
}
);
}
Future<List<Item>> fetchItems() {
final inventoryService = ref.watch(serviceProvider);
Future<List<Item>> items = inventoryService.fetchData();
return items;
}
_futureBuilder() {
return FutureBuilder<List<Item>>(
future: fetchItems(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
loading = false;
final result = snapshot.data;
if (result is Error) {
const errorMessage = 'Problems getting data';
return const Center(
child: Text(
errorMessage,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 18.0),
),
);
}
return _buildItemList(result!);
}
else {
return const SliverFillRemaining(
child: Center(
child: CircularProgressIndicator(),
),
);
}
}
);
}
这是 fetchData 函数的服务提供者,也是在 main 上启动的 serviceProvider。
Future loadItems() async {
var jsonString = await rootBundle.loadString('assets/inventorylist.json');
inventoryResult =
InventoryResult.fromJson(jsonDecode(jsonString));
}
@override
Future<List<Item>> fetchData() async {
_currentItems = inventoryResultsToItems(inventoryResult) as Future<List<Item>>;
return _currentItems ?? Future.error('No data found');
}
最后这是Main.app。由于 Flutter 永远不会加载,我想我正在创建某种无响应的竞争条件。
Future<void> main() async {
//RUNAPP FOR RIVERPOD IMPLEMENTATION
final service = await JsonInventoryService.create(); //runs loadItems()
runApp(ProviderScope(overrides: [
serviceProvider.overrideWithValue(service),
], child: const MyApp()));
//runApp(const MyApp());
}
这会导致手机模拟器无限期地卡在 Flutter 徽标上。我知道我的错误很简单,因为我上个月刚刚开始学习 Flutter,但感谢任何帮助。
根据评论建议进行一些更正。不是从 FutureBuilder 获取数据,而是在主类的开头添加以下内容:
class _InventoryScreenState extends ConsumerState<InventoryScreen> {
final inventoryService = ref.watch(serviceProvider);
Future<List<Item>> currentItemList = inventoryService.fetchData();
现在裁判不能直接从班级下被认可。
The instance member 'ref' can't be accessed in an initializer.
在 fetchData() 函数中没有收到错误。我添加了一个 Late 关键字来解决这个问题。 另一个错误是我忘记将此 json 文件添加到我的 /assets 文件夹中。