Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
      });
    });
  }```


 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...