Home > Enterprise >  Number of SR keep incrementing whenver i re-entre the list interface
Number of SR keep incrementing whenver i re-entre the list interface

Time:10-27

I'm getting the data from an API and storing it in a listview. I am setting the title in the appbar to get the srAttributes.length (all data) at first and then after the filter I get the SrForDisplay (the filtered list of data). Normally, there are 144 items of data, but whenever I go out and come back, it keeps incrementing. So, at first 144, then 288, then 483. The list of filtered data also keeps doubling and it's showing the correct number, so I have 2 shown, but I get 4 in the appbar. How do I fix this?

import 'dart:convert';
import 'dart:io';
import 'package:az/Actifs.dart';
import 'package:az/SR_Details.dart';
import 'package:az/main.dart';
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'class/sr.dart';

class DataFromAPI extends StatefulWidget {
  @override
  _DataFromAPIState createState() => _DataFromAPIState();
}

List<Sr> _MyAllData=[];
List<Sr> _SrForDsiplay=[];
Map<String, Color>  map={
"QUEUED":Color.fromARGB(255, 255, 136, 0),
"CLOSED":Colors.grey,
"Rejeced":Colors.red,
"INPROG":Colors.green,
"PENDING":Colors.blue,
"RESOLVED":Colors.green,
"NEW":Colors.blue,
};
Map<String, String>  map1={
"1":"Urgent",
"2":"High",
"3":"Medium",
"4":"Low",
};
/*Map<String, Color>  map3={
"Urgent":Colors.red,
"High":Color.fromARGB(255, 255, 139, 131),
"Medium":Colors.blue,
"Low":Colors.green,
"null":Colors.grey,
};*/
class _DataFromAPIState extends State<DataFromAPI> {
String title_string = "Liste des SR :";
  @override
  void initState() {
    loadData().then((value) {
      setState(() {
        _MyAllData.addAll(value);  
        _SrForDsiplay=_MyAllData;
      });
    });
    super.initState();
  }

  Future<List<Sr>> loadData() async {
    try {
      var response = await http.get(Uri.parse(
        'http://192.168.1.59:9080/maxrest/rest/mbo/sr/?_lid=maxadmin&_lpwd=maxadmin&_format=json'));
      if (response.statusCode == 200) {
        final jsonBody = json.decode(response.body);
        Demandes data = Demandes.fromJson(jsonBody);
        final srAttributes = data.srMboSet.sr;
        title_string='Liste des SR : ${srAttributes.length.toString()}';
        return srAttributes;
       }
       } catch (e) {
      throw Exception(e.toString());
    }
    throw Exception("");
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner:false,
      home: new Scaffold(resizeToAvoidBottomInset: false ,
        appBar: AppBar(
          title: Text(title_string),
          leading: IconButton(
              icon: Icon(Icons.arrow_back), onPressed: () {  Navigator.push(
                  context, MaterialPageRoute(builder: (context) => Home())); },
             ),
             flexibleSpace: InkWell(onTap: () {
               
             },),
         ),
        body: FutureBuilder<List<Sr>?>(
          future: loadData(),
          builder: (context, snapshot) {  
            if (_MyAllData.isEmpty) {
              return SizedBox(
          height: MediaQuery.of(context).size.height / 1.3,
          child: Center(
           child: CircularProgressIndicator(),
            ),
           );
            } else { return
             ListView(
              children: <Widget>[Padding(
             padding: const EdgeInsets.all(8.0),
             child: TextField(
               decoration:
               InputDecoration(icon: Icon(Icons.search), hintText: "Enter id or description"),
               onChanged: (text) {
               text=text.toLowerCase();
                setState(() {
               _SrForDsiplay =_MyAllData.where((srAttributes) {
                var srDescription = srAttributes.attributes.description!.content.toString().toLowerCase();
                var srID= srAttributes.attributes.ticketid.content.toString();
                return srDescription.contains(text) || srID.contains(text); 
                }).toList();
                title_string='Liste des SR : ${_SrForDsiplay.length.toString()}';
                print(title_string);
                      }
                    );
                  },
                ),
               ),
               new ListView.builder(scrollDirection: Axis.vertical,
                shrinkWrap: true,
                itemCount: _SrForDsiplay.length,
                itemBuilder: ((_, index) {
                  return
                        new ListTile(
                          title: new Card(
                            margin: new EdgeInsets.symmetric(
                                vertical: 2.0, horizontal: 8.0),
                            elevation: 10,
                            child: new ListTile(
                              title: new Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Padding(padding: new EdgeInsets.all(2.0)),
                                  Row(children :[
                                    Container(
                                     decoration: BoxDecoration(
                                     border: Border.all(
                                     color: Color.fromARGB(255, 255, 255, 255),
                                     ),
                                     color: map['${_SrForDsiplay[index].attributes.status.content}'],
                                     borderRadius: BorderRadius.all(Radius.circular(20)),
                                     ),
                                     child:Text('  ${_SrForDsiplay[index].attributes.status.content}  '),
                                   ),
                                    Container(child: Text('  '),),
                                   Container(
                                     decoration: BoxDecoration(
                                      border: Border.all(
                                      color: Color.fromARGB(255, 255, 255, 255),
                                     ),
                                     color:Colors.grey,
                                     borderRadius: BorderRadius.all(Radius.circular(20)),
                                     ),
                                     child:Text( map1['${_SrForDsiplay[index].attributes.reportedpriority?.content}'] ?? " null "),
                                       ),
                                      ],
                                     ),
                                    SizedBox( 
                                     height: 8,
                                     ),
                                  Row(children: <Widget>[
                                      Expanded( child: Container(child: Text('${_SrForDsiplay[index].attributes.description?.content}',style: GoogleFonts.openSans(
                                                  textStyle: TextStyle(
                                                  fontSize: 16,
                                                  fontWeight: FontWeight.w600)),),),),
                                       Expanded(child: Container(child:Text( '  ${_SrForDsiplay[index].attributes.ticketid.content}',style: GoogleFonts.openSans(
                                                  textStyle: TextStyle(
                                                  fontSize: 14,
                                                  fontWeight: FontWeight.w400)),)))
                                     ],),
                                       new Divider(
                                       color: Color.fromARGB(255, 110, 109, 109),
                                     ),
                                  Text(
                                    'Reported : ${DateFormat.yMMMMEEEEd().format(DateTime.parse('${_SrForDsiplay[index].attributes.statusdate.content}' ))}' ,
                                 style: GoogleFonts.openSans(
                                                  textStyle: TextStyle(
                                                  fontSize: 16,
                                                  fontWeight: FontWeight.w400)),
                                    ),
                                  new Text(
                                      'Reported by  : ${_SrForDsiplay[index].attributes.reportedby?.content}',style: GoogleFonts.openSans(
                                                  textStyle: TextStyle(
                                                  fontSize: 16,
                                                  fontWeight: FontWeight.w400)),
                                  ),
                                  Row(children: [new Image(image: AssetImage('assets/courroi.png'), width: 20),
                                      Text(
                                      '${_SrForDsiplay[index].attributes.assetnum?.content}'),], ),
                                  Row(children: [new Image(image: AssetImage('assets/emp.png'), width: 20),
                                      Text(
                                      '${_SrForDsiplay[index].attributes.assetsiteid?.content}'),], ) ,
                                       Divider(
                                        color: Color.fromARGB(255, 110, 109, 109),
                                     ),
                                     Row(children:[
                                      Expanded(child: Badge(            
                                        position: BadgePosition.topEnd(top: -8, end: 20),
                                        badgeColor: Colors.grey,
                                        badgeContent: Text('1'),
                                        child :IconButton(icon :Icon(Icons.file_present_rounded),  padding: const EdgeInsets.all(0),
                                        onPressed: () {
                                        },
                                        ),
                                      )
                                        ),
                                      Expanded(child: IconButton ( 
                                        icon: Icon(Icons.file_copy),
                                        onPressed: () {  }, 
                                        ),),
                                      Expanded(child:  IconButton(onPressed:() {  
                                      }, icon: Icon(Icons.delete))  )
                                        ],)
                                ],  
                              ),
                              trailing: Icon(Icons.arrow_forward_ios_rounded),
                              
                            ),
                          ),
                          onTap: () {
                       Navigator.push(
                      context,MaterialPageRoute(builder: (context) =>SrDetailsScreen(sr: _SrForDsiplay[index])),
                     );
                    }
                  );
                 }
                ),
               )
              ]);
            }
          },
        ),
      ),
    );
  }
}

CodePudding user response:

You need to clear the list before you load it again in your initState method. Clear Method

@override
void initState() {
  loadData().then((value) {
    _MyAllData.clear();
    setState(() {
      _MyAllData.addAll(value);  
      _SrForDsiplay=_MyAllData;
    });
  });
  super.initState();
}
  • Related