3

I've tried this code for searching jobs in listview but the data is not shown in listview. I think JSON is not parsing properly for Jobs data.

Here is the code of the model:

import 'package:flutter/material.dart';

class JobItem {
  final String title;
  final String description;

  JobItem(
      { 
      required this.title,
        required this.description,
        });

  factory JobItem.fromJson(Map<String, dynamic> json) {
    return JobItem(
      title: json['title'] as String,
      description: json['description'] as String,
    );
  }
}

Here I've written code for the main file to search data from the listview.

 List<JobItem> users = [];
  List<JobItem> filteredUsers = [];
  static String url = 'https://hospitality92.com/api/jobsbycategory/All';

  static Future<List<JobItem>> getJobsData() async {
    try {
      final response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        List<JobItem> list = parseAgents(response.body);

        return list;
      } else {
        throw Exception('Error');
      }
    } catch (e) {
      throw Exception(e.toString());
    }
  }
  static List<JobItem> parseAgents(String responseBody) {
    final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
    return parsed.map<JobItem>((json) => JobItem.fromJson(json)).toList();
  }


  @override
  void initState() {
    super.initState();
    getJobsData().then((usersFromServer) {
      setState(() {
        users = usersFromServer;
        filteredUsers = users;
      });
    });
  }```


 
1
  • have you checked the value from getJobData() Commented Aug 16, 2021 at 10:01

2 Answers 2

4

Try below code your problem has been solved :

//declare packages
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;

class Jobs extends StatefulWidget {
  Jobs() : super();

  @override
  JobsState createState() => JobsState();
}

class Debouncer {
  final int milliseconds;
  VoidCallback action;
  Timer _timer;

  Debouncer({this.milliseconds});

  run(VoidCallback action) {
    if (null != _timer) {
      _timer.cancel();
    }
    _timer = Timer(Duration(milliseconds: milliseconds), action);
  }
}

class JobsState extends State<Jobs> {
  final _debouncer = Debouncer(milliseconds: 500);

  List<Subject> subjects = [];
  List<Subject> filteredSubjects = [];
  //API call for All Subject List

  static String url = 'https://hospitality92.com/api/jobsbycategory/All';

  static Future<List<Subject>> getAllSubjectsList() async {
    try {
    final response = await http.get(Uri.parse(url));

    if (response.statusCode == 200) {
      print(response.body);
      List<Subject> list = parseAgents(response.body);

      return list;
    } else {
      throw Exception('Error');
    }
    } catch (e) {
      throw Exception(e.toString());
    }
  }

  static List<Subject> parseAgents(String responseBody) {
    final parsed =
        json.decode(responseBody)['jobs'].cast<Map<String, dynamic>>();
    return parsed.map<Subject>((json) => Subject.fromJson(json)).toList();
  }

  @override
  void initState() {
    super.initState();
    getAllSubjectsList().then((subjectFromServer) {
      setState(() {
        subjects = subjectFromServer;
        filteredSubjects = subjects;
      });
    });
  }

  //Main Widget
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'All Subjects',
          style: TextStyle(fontSize: 25),
        ),
      ),
      body: Column(
        children: <Widget>[
          //Search Bar to List of typed Subject
          Container(
            padding: EdgeInsets.all(15),
            child: TextField(
              textInputAction: TextInputAction.search,
              decoration: InputDecoration(
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(25.0),
                  borderSide: BorderSide(
                    color: Colors.grey,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20.0),
                  borderSide: BorderSide(
                    color: Colors.blue,
                  ),
                ),
                suffixIcon: InkWell(
                  child: Icon(Icons.search),
                ),
                contentPadding: EdgeInsets.all(15.0),
                hintText: 'Search ',
              ),
              onChanged: (string) {
                _debouncer.run(() {
                  setState(() {
                    filteredSubjects = subjects
                        .where((u) => (u.title
                            .toLowerCase()
                            .contains(string.toLowerCase())))
                        .toList();
                  });
                });
              },
            ),
          ),
          //Lists of Subjects
          Expanded(
            child: ListView.builder(
              shrinkWrap: true,
              physics: ClampingScrollPhysics(),
              padding: EdgeInsets.only(top: 20, left: 20, right: 20),
              itemCount: filteredSubjects.length,
              itemBuilder: (BuildContext context, int index) {
                return Card(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                    side: BorderSide(
                      color: Colors.grey[300],
                    ),
                  ),
                  child: Padding(
                    padding: EdgeInsets.all(5.0),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        ListTile(
                          leading: Text(
                            filteredSubjects[index].skills,
                          ),
                          title: Text(
                            filteredSubjects[index].title,
                            style: TextStyle(fontSize: 16),
                          ),
                          trailing: Text(filteredSubjects[index].position.toString()),
                        )
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

//Declare Subject class for json data or parameters of json string/data
//Class For Subject
  class Subject {
  String title;
  int id;
  String skills;
  String position;
  Subject({
    this.id,
    this.title,
    this.skills,
    this.position,
  });

  factory Subject.fromJson(Map<String, dynamic> json) {
    return Subject(
        title: json['title'] as String,
        id: json['id'],
        skills: json['skills'],
        position: json['positions']);
  }
}

Your screen before search: enter image description here

Your Screen after search : enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Will this cause the API endpoint to be hit again when a search term is inputted? Or does this just obtain all the data and then filter it as the user enters a search term?
@dingo can't understand can you explain in brief what do you want
0

U have a little mistake in parsing. I added response.body['jobs'].

static Future<List<JobItem>> getJobsData() async {
try {
  final response = await http.get(Uri.parse(url));
  if (response.statusCode == 200) {
    List<JobItem> list = parseAgents(Map<String, dynamic>.from(jsonDecode(response.body))['jobs']);

    return list;
  } else {
    throw Exception('Error');
  }
} catch (e) {
  throw Exception(e.toString());
} }

2 Comments

sir following error occurs. ** A value of type 'String' can't be assigned to a variable of type 'int'. List<JobItem> list = parseAgents(response.body['jobs']); **
I changed the function a bit. Try it now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.