Home > Software engineering >  flutter carousel slider doesn't refresh items
flutter carousel slider doesn't refresh items

Time:10-12

i am new at flutter, so i tried to implement carousel slider with images, i receive an List with my model from server and i created widget but it shows only 1 item from 18... I mean it always show 1 item, but all list is passed But if i make hot reload then i receive all items, i hope i could explain... my dart code

import 'dart:convert';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:vltest/Models/_easyloaderslist.dart';
import 'Models/_workers.dart';
import 'Widgets/navigation_drawer_widget.dart';
import 'database.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;

late List<EasyLoadersList> imgList = List.empty();

class Landing extends StatefulWidget {
  @override
  _LandingState createState() => _LandingState();
}

Future<List<EasyLoadersList>> _getLoaders(Workers workers) async {
  final response = await http.get(
      Uri.parse(
          'http://url'),
      headers: {
        "Content-Type": "application/json",
        "Authorization": "Bearer ${workers.token}"
      });

  if (response.statusCode == 200) {
    Iterable l = json.decode(response.body);
    List<EasyLoadersList> loaders = List<EasyLoadersList>.from(
        l.map((model) => EasyLoadersList.fromJson(model)));
    return loaders;
  } else {
    throw Exception('Failed to load album');
  }
}

List<T> map<T>(List list, Function handler) {
  List<T> result = [];
  for (var i = 0; i < list.length; i  ) {
    result.add(handler(i, list[i]));
  }

  return result;
}

showWorkerDialog(BuildContext context, Workers album) {
  // set up the button
  Widget okButton = TextButton(
    child: Text("OK"),
    onPressed: () {
      Navigator.pop(context);
    },
  );

  // set up the AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text(album.name),
    content: Text("Hi, ${album.name}"),
    actions: [
      okButton,
    ],
  );

  // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}

class _LandingState extends State<Landing> {
  String _username = "";
  late List<EasyLoadersList> loaders = List.empty();
  int _current = 0;
  @override
  void initState() {
    super.initState();
    _loadUserInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: NavigationDrawerWidget(),
      appBar: AppBar(
        title: Text('User info'),
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          _loadUserInfo();
        },
        child: Center(
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                CarouselSlider.builder(
                  itemCount: imgList.length,
                  itemBuilder: (context, index, realIndex) {
                    if (imgList.length != 0) {
                      return buildImage(imgList[index]);
                    } else {
                      return loadingData(context);
                    }
                  },
                  options: CarouselOptions(height: 500),
                ),
              ]),
        ),
      ),
    );
  }

  Widget buildImage(EasyLoadersList loadersList) => Column(
        mainAxisSize: MainAxisSize.max,
        children: [
          AspectRatio(
            aspectRatio: 1,
            child: Image.network(
              loadersList.url,
              fit: BoxFit.fill,
            ),
          ),
          const SizedBox(
            height: 30,
          ),
          Text("Address :"   loadersList.shopAddress),
          Text("Serial:"   loadersList.serialNumber),
          Text("Hours :"   loadersList.currentMotoHours),
          Text("Current:"   loadersList.currentMotoHoursUntilTO),
          Text("Next:"   loadersList.remainsMotoHoursUntilTO),
          Text("Last Use:"   loadersList.lastMotoHoursEditDate),
        ],
      );



  Widget loadingData(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            Text(
              'Loading...',
              style: Theme.of(context).textTheme.headline6,
            ),
            CircularProgressIndicator(
              semanticsLabel: 'Loading...',
            ),
          ],
        ),
      ),
    );
  }


  Future<void> _loadUserInfo() async {
    Workers workers = await DBProvider.db.getWorkerInfo();
    final prefs = await SharedPreferences.getInstance();
    showWorkerDialog(context, workers);
    imgList = await _getLoaders(workers);
  }
}

CodePudding user response:

Cant see any setState to update the UI. try adding setState on end of refresh like.

onRefresh: () async {
   await  _loadUserInfo();
   setState((){});   
  },

And on initState

_loadUserInfo().then((value) {setState((){})}):

Or

Future<void> _loadUserInfo() async {
  .....
  imgList = await _getLoaders(workers);
  setState((){});
}
  • Related