【发布时间】:2021-05-12 13:07:15
【问题描述】:
我正在调用一个 API 来过滤带有地区的国家列表。每当我选择区域时,它都会过滤并显示所选区域的所有国家/地区。我正在使用searchable_dropdown 包进行过滤。
我的可搜索下拉过滤器工作正常,但如果不从下拉列表中选择,则无法获取所有数据。
我想要什么:-我想在应用程序运行时或在 屏幕截图 1 中未从下拉列表中选择任何区域时显示来自 api 的所有可用数据。
我的代码在下面
Main.dart
import 'package:flutter/material.dart';
import 'package:searchable_dropdown_flutter/searchable_dropdown1.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SearchableDropdownApp(),
);
}
}
searchable_dropdown.dart
import 'package:flutter/material.dart';
import 'package:searchable_dropdown/searchable_dropdown.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
class SearchableDropdownApp extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
class _AppState extends State<SearchableDropdownApp> {
Map<String, String> selectedValueMap = Map();
// ignore: deprecated_member_use
List filteredData = List();
// ignore: deprecated_member_use
List filteredDataAll = List();
// ignore: deprecated_member_use
List alldata = List();
@override
void initState() {
selectedValueMap["server"] = null;
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('Searchable Dropdown Example App'),
),
body: FutureBuilder(
// get data from server and return a list of mapped 'name' fields
future:
getServerData(), //sets getServerData method as the expected Future
// ignore: missing_return
builder: (context, snapshot) {
if (snapshot.hasData) {
// ignore: deprecated_member_use
List<String> countries = new List();
for (int i = 0; i < snapshot.data.length; i++) {
if (!countries.contains(snapshot.data[i]['region']))
countries.add(snapshot.data[i]['region']);
}
alldata = snapshot.data;
//checks if response returned valid data
// use mapped 'name' fields for providing options and store selected value to the key "server"
return getSearchableDropdown(countries, "server", alldata);
} else if (snapshot.hasError) {
//checks if the response threw error
return Text("${snapshot.error}");
}
return Center(child: CircularProgressIndicator());
},
),
),
);
}
Widget getSearchableDropdown(List<String> listData, mapKey, alldata) {
List<DropdownMenuItem> items = [];
for (int i = 0; i < listData.length; i++) {
items.add(new DropdownMenuItem(
child: new Text(
listData[i],
),
value: listData[i],
));
}
return Scaffold(
body: Column(
children: [
SearchableDropdown(
isExpanded: true,
style: TextStyle(color: Colors.red),
items: items,
value: selectedValueMap[mapKey],
isCaseSensitiveSearch: false,
hint: new Text('Select Country'),
searchHint: new Text(
'Select Country',
style: new TextStyle(fontSize: 20),
),
onChanged: (value) {
setState(() {
selectedValueMap[mapKey] = value;
print('selectedValueMap[mapKey]');
print(selectedValueMap[mapKey]);
// ignore: deprecated_member_use
filteredData = new List();
for (int i = 0; i < alldata.length; i++) {
if (alldata[i]['region'] == selectedValueMap[mapKey])
filteredData.add(alldata[i]);
}
filteredDataAll = filteredData.toList();
print('filteredDataAll ka data');
});
},
),
Text(selectedValueMap[mapKey].toString()),
Text('data'),
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: filteredDataAll.length,
itemBuilder: (context, index) {
return SingleChildScrollView(
child: Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(filteredDataAll[index].toString()),
],
),
)),
);
}),
),
),
],
),
);
}
Future<List> getServerData() async {
String url =
'https://restcountries.eu/rest/v2/all?fields=name;capital;alpha3Code;region;population;';
final response =
await http.get(url, headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
List<dynamic> responseBody = json.decode(response.body);
return responseBody;
} else {
print("error from server : $response");
throw Exception('Failed to load post');
}
}
}
屏幕截图
应用程序首次运行时 SecreenShots 1
从过滤器中选择之后 SecreenShots 2
【问题讨论】:
-
您到底面临什么问题?
-
当应用程序运行时,没有数据显示,如屏幕截图 1 所示,但我想在没有从过滤器中选择任何数据时显示所有可用数据。
标签: android flutter dart dropdown