skip to Main Content

I’m getting a list of image urls from api. I am showing image at zero index on loading api. There’s a slider widget, on changing it i put the value as image index and show images based on that. But when i load next image theres a white space which keeps showing. I want it to be smooth as if i am watching a timelapse. I have attached the image below on slider change i want to next image. I used precacheimage as well but it is still showing whitespace/loading when i move slider.

Future<void> preloadImages(List<String> imageUrls) async {
for (String url in imageUrls) {
  await precacheImage(CachedNetworkImageProvider(url), context);
}
this.imageUrls = imageUrls;

}

enter image description here

2

Answers


  1. Chosen as BEST ANSWER
    AspectRatio(
                      aspectRatio: 16 / 9,
                      child: imageBytesList.isNotEmpty
                          ? Image.memory(
                              // Use the preloaded image bytes instead of fetching from the network
                              // imageBytesList.isNotEmpty ?
                              Uint8List.fromList(currentBytes!),
                              gaplessPlayback: true,
                              
                              // : imageBytesList.first,
                              width: double.infinity,
                              fit: BoxFit.fill,
                              errorBuilder: (BuildContext context,
                                  Object exception, StackTrace? stackTrace) {
                                return ClipRRect(
                                  child: Image.asset(
                                    'assets/images/error_image.jpeg',
                                    fit: BoxFit.cover,
                                  ),
                                );
                              },
                            )
                          : ClipRRect(
                              child: Image.asset(
                                'assets/images/error_image.jpeg',
                                fit: BoxFit.cover,
                              ),
                            ),
                    ),
                    Slider(
                      activeColor: Helper.primary,
                      thumbColor: Colors.white,
                      min: 0,
                      max: data.length.toDouble() - 1,
                      value: _currentSliderValue,
                      onChangeEnd: (value){
                        setState(() {
                          print("onchnagestart" + value.toString());
                        });
                      },
                      onChanged: (value) {
                        setState(() {
                          _currentSliderValue = value;
                          currentBytes = imageBytesList[value.round()];
                          // currentslider = value.round();
                          print(value.toString());
                        });
                        // setState(() {});
                      },
                    ), this is my code
    

  2. import 'dart:collection';
    
    import 'package:cached_network_image/cached_network_image.dart';
    import 'package:carousel_slider/carousel_slider.dart';
    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert' as convert;
    
    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 Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        CarouselSlider.builder(
                          itemCount: snapshot.data?.length ?? 0,
                          itemBuilder: (BuildContext context, int itemIndex,
                                  int pageViewIndex) =>
                              SizedBox(
                            height: 200,
                            child: CachedNetworkImage(
                              imageUrl: snapshot.data[_currentSliderValue.toInt()],
                              placeholder: (context, url) =>
                                  const CircularProgressIndicator(),
                              errorWidget: (context, url, error) =>
                                  const Icon(Icons.error),
                            ),
                          ),
                          options: CarouselOptions(
                            autoPlay: false,
                            enlargeCenterPage: true,
                            viewportFraction: 0.9,
                            aspectRatio: 2.0,
                            initialPage: _currentSliderValue.toInt(),
                          ),
                        ),
                        Slider(
                          value: _currentSliderValue,
                          max: 20,
                          divisions: 5,
                          label: _currentSliderValue.round().toString(),
                          onChanged: (double value) {
                            setState(() {
                              _currentSliderValue = value;
                            });
                          },
                        ),
                      ],
                    );
                  }
                }
                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}.');
        }
      }
    }
    

    Output

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search