在颤振中使用列表视图搜索数据时出错
Posted
技术标签:
【中文标题】在颤振中使用列表视图搜索数据时出错【英文标题】:Error in searching data using listview in flutter 【发布时间】:2021-10-18 09:14:38 【问题描述】:我已尝试使用此代码在列表视图中搜索工作,但数据未显示在列表视图中。我认为 JSON 无法正确解析 Jobs 数据。
这是模型的代码:
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,
);
这里我已经为主文件编写了代码来从列表视图中搜索数据。
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;
);
);
```
【问题讨论】:
你检查过getJobData()
的值吗
【参考方案1】:
你在解析时有一点错误。我加了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());
【讨论】:
先生出现以下错误。 ** 不能将“String”类型的值分配给“int”类型的变量。 List试试下面的代码你的问题已经解决了:
//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']);
搜索前您的屏幕:
搜索后您的屏幕:
【讨论】:
以上是关于在颤振中使用列表视图搜索数据时出错的主要内容,如果未能解决你的问题,请参考以下文章