Me indicaron que hiciera una búsqueda desplegable que es dependiente, una tiene que ser "Regiones" y la otra "Comunas". Todo esto tiene que venir de un JSON local. La idea es que en el primer dropdown elijas la región y en el segundo se muestre las comunas que tiene esa región. Ya tengo el primer dropdown cargado con la data de regiones.
Lo que no veo aún es cómo hago que ese segundo dropdown sea dependiente del primero y dónde debería agregarlo. Aún se me complica la jerarquía de árbol que tiene Flutter.
Home
class HomePage extends GetView<HomeController> {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
HomeController controller = Get.find<HomeController>();
var title = "HomePage";
return Scaffold(
body: Obx(() {
HomeController controller = Get.find<HomeController>();
return controller.regionList.isEmpty
? const Center(
child: Text('No hay regiones'),
)
: Center(
child: Padding(
padding: const EdgeInsets.all(26),
child: FutureBuilder<List<Region>>(
future: controller.getRegiones(),
builder: (context, snapshot) {
if (snapshot.hasData) {
List<Region>? data = snapshot.data;
return Column(
children: [
DropdownSearch<Region>(
popupProps:
const PopupProps.menu(showSearchBox: true),
asyncItems: (String filter) =>
controller.getRegiones(),
itemAsString: (Region u) => u.name ?? "",
onChanged: (Region? data) => print(data?.name),
dropdownDecoratorProps:
const DropDownDecoratorProps(
dropdownSearchDecoration: InputDecoration(
labelText: "Region",
hintText: "Seleccione una region",
),
),
),
DropdownSearch<Region>(
asyncItems: (String filter) =>
controller.getRegiones(),
itemAsString: (Region u) => u.communes[1].name,
onChanged: (Region? data) =>
print(data?.communes[1].name),
dropdownDecoratorProps:
const DropDownDecoratorProps(
dropdownSearchDecoration: InputDecoration(
labelText: "Comunas",
hintText: "Seleccione una comuna",
),
),
)
],
);
} else {
return const CircularProgressIndicator();
}
}),
));
}),
);
}
}
homeController
class HomeController extends GetxController {
final RxList<Region> regionList = <Region>[].obs;
void setSelected(String value) {
regionList.value = value as List<Region>;
}
Future<List<Region>> getRegiones() async {
var response = await rootBundle.loadString('assets/response.json');
var results = (jsonDecode(response)['regions'] ?? []) as List;
return results.map((x) => Region.fromJson(x)).toList();
}
@override
Future<void> onInit() async {
// TODO: implement onInit
super.onInit();
regionList.assignAll(await getRegiones());
}
}
Modelo
import 'dart:convert';
Regiones regionesFromJson(String str) => Regiones.fromJson(json.decode(str));
String regionesToJson(Regiones data) => json.encode(data.toJson());
class Regiones {
Regiones({
required this.name,
required this.regions,
});
String name;
List<Region> regions;
factory Regiones.fromJson(Map<String, dynamic> json) => Regiones(
name: json["name"],
regions:
List<Region>.from(json["regions"].map((x) => Region.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"name": name,
"regions": List<dynamic>.from(regions.map((x) => x.toJson())),
};
}
class Region {
Region({
required this.name,
required this.romanNumber,
required this.number,
required this.abbreviation,
required this.communes,
});
String? name;
String? romanNumber;
String? number;
String? abbreviation;
List<Commune> communes;
factory Region.fromJson(Map<String, dynamic> json) => Region(
name: json["name"],
romanNumber: json["romanNumber"],
number: json["number"],
abbreviation: json["abbreviation"],
communes: List<Commune>.from(
json["communes"].map((x) => Commune.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"name": name,
"romanNumber": romanNumber,
"number": number,
"abbreviation": abbreviation,
"communes": List<dynamic>.from(communes.map((x) => x.toJson())),
};
}
class Commune {
Commune({
required this.name,
required this.identifier,
});
String name;
String identifier;
factory Commune.fromJson(Map<String, dynamic> json) => Commune(
name: json["name"],
identifier: json["identifier"] ?? '',
);
Map<String, dynamic> toJson() => {
"name": name,
"identifier": identifier,
};
}
JSON
{
"name": "Chile",
"regions": [
{
"name": "Arica y Parinacota",
"romanNumber": "XV",
"number": "15",
"abbreviation": "AP",
"communes": [
{ "name": "Arica", "identifier": "XV-1" },
{ "name": "Camarones", "identifier": "XV-2" },
{ "name": "General Lagos", "identifier": "XV-3" },
{ "name": "Putre", "identifier": "XV-4" }
]
}...