简体   繁体   中英

Flutter: How to prioritize displaying the image from Asset, if it can't be found, then display image from URL?

This is JSON file:

[
  {
    "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"
    }
  }
]

In assets, I created 3 image files: "us.png", "de.png", "gb.png" and I have created a ListView to display data from the JSON file. So I want to set the following condition:

1. Display images in assets of the same name as imageResName first (Ex. "us.png" with country: United States )
2. In case the file "us.png" cannot be found in assets, then it will display from the image from imageUrl .

This is main.dart file

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(),
                        );
                      }
                    }))));
  }
}


I had the same problem. Just use FadeInImage as the following:

FadeInImage(
                    width: 50,
                    height: 50,
                    fit: BoxFit.fill,
                    image: AssetImage(localPath),
                    placeholder: NetworkImage(urlPath),
              ),

Make sure your image: is your local asset while the placeholder: is your remote image.

Enjoy!

create a variable

String localImage = "assets/images/1.jpg";

this your logic but you need to find a way to check if localImage exist in locally i dont know how why you want to do that, thats why i cant tell what logic you need to use, but this is your solution

leading: CircleAvatar(
// localImage = "assets/images/1.jpg"
    backgroundImage: localImage != null ? AssetImage(localImage) :  NetworkImage(countries[index].image.imageUrl),),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM