Search code examples
flutterimagedartlistview

How to display an image in listview builder


I took pictures to show in listview builder, but I found that my images are not showing. I use image.network to pull the picture to show which my pictures are stored in the folder Problem_image and the name of the image is stored in the database. How can I modify it to show my image?

Enter image description here

Expanded(
    child: StreamBuilder(
       stream: _streamController.stream,
       builder: (context, snapshots) {
        if (snapshots.hasData) {
          return ListView.builder(
              itemCount: problemlist.length,
               itemBuilder: ((context, index) {
                 problemModel problem = problemlist[index];
                 return Card(
                  margin: EdgeInsets.all(10),
                  child: ListTile(
                    leading: Image.network(
                      'http://192.168.1.148/skc/Problem_image/${problem.image}',
                      fit: BoxFit.cover,
                      width: 100,
                    ),
                    title: Text(
                      problem.name_surname,
                      style: TextStyle(
                          fontWeight: FontWeight.bold, fontSize: 19),
                    ),
                    subtitle: Text(
                      problem.status,
                      style: TextStyle(
                          fontWeight: FontWeight.bold, fontSize: 17),
                    ),
                    trailing: Text(
                     problem.area,
                     style: TextStyle(
                          fontWeight: FontWeight.bold, fontSize: 16),
                    ),
                  ),
                );
              }));
        }
         return Center(
          child: CircularProgressIndicator(),
        );
      },
    ),
)

Solution

  • It seems your URL is not reachable. You can try this way:

    import 'package:flutter/material.dart';
    import 'dart:collection';
    import 'package:cached_network_image/cached_network_image.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert' as convert;
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
            useMaterial3: true,
          ),
          home: const MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({super.key});
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      final queryParameters = {
        'country': 'us',
        'category': 'business',
        'apiKey': 'Your API Key',
      };
      //Get API key from https://newsapi.org/
    
      HashMap<dynamic, dynamic> data = HashMap<dynamic, dynamic>();
      double _currentSliderValue = 0;
      late final Future myFuture;
    
      @override
      void initState() {
        myFuture = apiCall();
    
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: FutureBuilder(
              future: myFuture,
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  if (snapshot.hasError) {
                    return const Center(child: Text("No data available"));
                  } else if (snapshot.hasData) {
                    return SizedBox(
                      child: ListView.builder(
                        itemCount: snapshot.data?.length ?? 0,
                        scrollDirection: Axis.vertical,
                        itemBuilder: (context, index) {
                          return Card(
                            margin: const EdgeInsets.all(10),
                            child: ListTile(
                              leading: SizedBox(
                                width: 100,
                                child: CachedNetworkImage(
                                  fit: BoxFit.fitHeight,
                                  imageUrl:
                                      snapshot.data[_currentSliderValue.toInt()],
                                  placeholder: (context, url) =>
                                      const CircularProgressIndicator(),
                                  errorWidget: (context, url, error) =>
                                      const Icon(Icons.error),
                                ),
                              ),
                              title: const Text("Your Title here"),
                              subtitle: const Text("Your SubTitle here"),
                              trailing: const Text("Your Training here"),
                            ),
                          );
                        },
                      ),
                    );
                  }
                }
                return const Center(child: CircularProgressIndicator());
              }),
        );
      }
    
      Future apiCall() async {
        List<String> list = [];
        var url = Uri.https('newsapi.org', 'v2/top-headlines', queryParameters);
    
        var response = await http.get(url);
        if (response.statusCode == 200) {
          var jsonResponse =
              convert.jsonDecode(response.body) as Map<String, dynamic>;
    
          var articles = jsonResponse['articles'];
    
          for (var i = 0; i < articles.length; i++) {
            var articleData = articles[i];
            var urls = articleData["urlToImage"];
            if (urls != null) {
              list.add(urls);
            }
          }
    
          return list;
        } else {
          debugPrint('Request failed with status: ${response.statusCode}.');
        }
      }
    }
    

    Enter image description here