【发布时间】:2020-09-11 09:50:19
【问题描述】:
这是 JSON 文件:
[
{
"id": 1,
"country": "United States",
"image": {
"imageResName": "us.png",
"imageUrl": "https://www.countryflags.io/US/shiny/64.png"
}
},
{
"id": 2,
"country": "Germany",
"image": {
"imageResName": "de.png",
"imageUrl": "https://www.countryflags.io/DE/shiny/64.png"
}
},
{
"id": 3,
"country": "United Kingdom",
"image": {
"imageResName": "gb.png",
"imageUrl": "https://www.countryflags.io/GB/shiny/64.png"
}
}
]
在资产中,我创建了 3 个图像文件:“us.png”、“de.png”、“gb.png”,并创建了一个 ListView 来显示 JSON 文件中的数据。所以我想设置以下条件:
1.首先在与imageResName 同名的资产中显示图像
(例如,带有country: United States 的“us.png”)
2.如果资产中找不到文件“us.png”,那么它将
从图像显示
imageUrl.
这是 main.dart 文件
import 'dart:convert';
import 'package:ask/country.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<List<Country>> getCountryFromJson(BuildContext context) async {
String jsonString =
await DefaultAssetBundle.of(context).loadString('assets/country.json');
List<dynamic> raw = jsonDecode(jsonString);
return raw.map((e) => Country.fromJson(e)).toList();
}
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Country')),
body: Container(
child: FutureBuilder(
future: getCountryFromJson(context),
builder: (context, data) {
if (data.hasData) {
List<Country> countries = data.data;
return ListView.builder(
itemCount: countries.length,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
backgroundImage: AssetImage('assets/${countries[index].image.imageResName}
// 1. Prioritize displaying image from Asset
// 2. If it can't find then display image from url
// NetworkImage(countries[index].image.imageUrl),
),
title: Text(countries[index].country),
);
});
} else {
return Center(
child: CircularProgressIndicator(),
);
}
}))));
}
}
【问题讨论】:
标签: json image listview flutter dart