Created
August 1, 2022 06:38
-
-
Save okelloEnos/034692368d3cc6f1a8c0cdf11afa86f5 to your computer and use it in GitHub Desktop.
A screen that can capture fields depending on previous selected item using dropdown field and fetching from api request. e.g You have to select a County before having the ability to select a Sub County in Kenya
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:io'; | |
import 'package:dio/dio.dart'; | |
import 'package:flutter/material.dart'; | |
import 'package:maisha_loan/model/location_info.dart'; | |
import 'package:maisha_loan/resources/dio_exceptions.dart'; | |
import 'package:maisha_loan/resources/values.dart'; | |
class CountrySelection extends StatefulWidget { | |
const CountrySelection({Key? key}) : super(key: key); | |
@override | |
State<CountrySelection> createState() => _CountrySelectionState(); | |
} | |
class _CountrySelectionState extends State<CountrySelection> { | |
@override | |
void initState() { | |
// _generateList(); | |
countiesList(); | |
super.initState(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('Dynamic stuff'), | |
), | |
body: Column( | |
mainAxisAlignment: MainAxisAlignment.start, | |
children: [ | |
Container( | |
alignment: Alignment.topCenter, | |
margin: const EdgeInsets.only(bottom: 100, top: 100), | |
child: Text('KD Techs'), | |
), | |
//======================================================== county | |
Container( | |
padding: const EdgeInsets.only(right: 15, left: 15, top: 5), | |
color: Colors.white, | |
child: Row( | |
mainAxisAlignment: MainAxisAlignment.spaceBetween, | |
children: [ | |
Expanded(child: DropdownButtonHideUnderline(child: ButtonTheme( | |
alignedDropdown: true, | |
child: DropdownButton<String>( | |
value: countyId, | |
iconSize: 30, | |
icon: (null), | |
style: TextStyle(color: Colors.black54, fontSize: 16), | |
hint: Text('Select County'), | |
items: allCountiesList.map((item){ | |
return DropdownMenuItem( | |
child: item.code == 0 ? new Text("${item.name}") : new Text("${item.name}"), | |
value: item.code.toString(), | |
); | |
}).toList(), | |
onChanged: (String? newValue){ | |
setState(() { | |
subCountyId = "0"; | |
wardId = "0"; | |
countyId = newValue ?? "1"; | |
subCountiesList(); | |
print(countyId); | |
}); | |
})))) | |
], | |
), | |
), | |
SizedBox( | |
height: 20, | |
), | |
// ======================================================== sub county | |
Container( | |
padding: EdgeInsets.only(left: 15, right: 15, top: 5), | |
color: Colors.white, | |
child: Row( | |
mainAxisAlignment: MainAxisAlignment.spaceBetween, | |
children: <Widget>[ | |
Expanded( | |
child: DropdownButtonHideUnderline( | |
child: ButtonTheme( | |
alignedDropdown: true, | |
child: DropdownButton<String>( | |
value: subCountyId, | |
iconSize: 30, | |
icon: (null), | |
style: TextStyle( | |
color: Colors.black54, | |
fontSize: 16, | |
), | |
hint: Text('Select Sub County'), | |
onChanged: (String? newValue) { | |
setState(() { | |
wardId = "0"; | |
subCountyId = newValue ?? "1"; | |
retrieveWardList(); | |
print(subCountyId); | |
}); | |
}, | |
items: subCountyList.map((item) { | |
return new DropdownMenuItem( | |
child: new Text("${item.name}"), | |
value: item.code.toString(), | |
); | |
}).toList(), | |
), | |
), | |
), | |
), | |
], | |
), | |
), | |
SizedBox( | |
height: 20, | |
), | |
// ========= ward | |
Container( | |
padding: EdgeInsets.only(left: 15, right: 15, top: 5), | |
color: Colors.white, | |
child: Row( | |
mainAxisAlignment: MainAxisAlignment.spaceBetween, | |
children: <Widget>[ | |
Expanded( | |
child: DropdownButtonHideUnderline( | |
child: ButtonTheme( | |
alignedDropdown: true, | |
child: DropdownButton<String>( | |
value: wardId, | |
iconSize: 30, | |
icon: (null), | |
style: TextStyle( | |
color: Colors.black54, | |
fontSize: 16, | |
), | |
hint: Text('Select Ward'), | |
onChanged: (String? newValue) { | |
setState(() { | |
wardId = newValue ?? "1"; | |
print(wardId); | |
}); | |
}, | |
items: wardList.map((item) { | |
return new DropdownMenuItem( | |
child: new Text("${item.name}"), | |
value: item.code.toString(), | |
); | |
}).toList(), | |
), | |
), | |
), | |
), | |
], | |
), | |
), | |
], | |
), | |
); | |
} | |
//=============================================================================== Api Calling here | |
// Get State information by API | |
LocationInfo defaultCountyOption = LocationInfo(id: 0, name: 'Select County', code: 0); | |
List<LocationInfo> allCountiesList = [LocationInfo(id: 0, name: 'Select County', code: 0)]; | |
String countyId = '0'; | |
/// retrieve list of counties | |
Future<List<LocationInfo>> countiesList() async{ | |
// SharedPreferences preferences = await SharedPreferences.getInstance(); | |
// String? token = preferences.getString(VALID_TOKEN); | |
var url = "/counties"; | |
BaseOptions options = BaseOptions( | |
baseUrl: "$locationUrl", | |
contentType: "application/json", | |
receiveDataWhenStatusError: true, | |
sendTimeout: DURATION_TIMEOUT, | |
connectTimeout: DURATION_TIMEOUT, | |
receiveTimeout: DURATION_TIMEOUT, | |
// headers: {"Authorization" : "Bearer $token"} | |
); | |
Dio dio = Dio(options); | |
try{ | |
final response = await dio.get(url); | |
int responseValue = response.data['response_code']; | |
switch(responseValue){ | |
case 1 : | |
List<LocationInfo> counties = List<LocationInfo>.from(response.data['data'].map((data) => LocationInfo.fromJson(data))); | |
setState(() { | |
allCountiesList = [...allCountiesList, ...counties]; | |
}); | |
return counties; | |
case 2: | |
final Map<String, dynamic> errors_map = response.data['errors']; | |
final List<dynamic> first_error_value = errors_map.values.first; | |
final error_content = first_error_value.first; | |
throw("$error_content"); | |
case 3: | |
default: | |
throw("something_went_wrong_text"); | |
} | |
} | |
on DioError catch(e){ | |
throw(DioExceptions.fromDioError(e)); | |
} | |
on SocketException catch(e){ | |
throw("data_connection_text"); | |
} | |
} | |
LocationInfo defaultSubCountyOption = LocationInfo(id: 0, name: 'Select Sub County', code: 0); | |
List<LocationInfo> subCountyList = [LocationInfo(id: 0, name: 'Select Sub County', code: 0)]; | |
String subCountyId = '0'; | |
/// retrieve list of sub counties | |
Future<List<LocationInfo>> subCountiesList() async{ | |
var url = "/sub-counties/$countyId"; | |
BaseOptions options = BaseOptions( | |
baseUrl: "$locationUrl", | |
contentType: "application/json", | |
receiveDataWhenStatusError: true, | |
sendTimeout: DURATION_TIMEOUT, | |
connectTimeout: DURATION_TIMEOUT, | |
receiveTimeout: DURATION_TIMEOUT, | |
// headers: {"Authorization" : "Bearer $token"} | |
); | |
Dio dio = Dio(options); | |
try{ | |
final response = await dio.get(url); | |
int responseValue = response.data['response_code']; | |
switch(responseValue){ | |
case 1 : | |
List<LocationInfo> subCounties = List<LocationInfo>.from(response.data['data'].map((data) => LocationInfo.fromJson(data))); | |
setState(() { | |
subCountyList = [defaultSubCountyOption, ...subCounties]; | |
}); | |
return subCounties; | |
case 2: | |
final Map<String, dynamic> errors_map = response.data['errors']; | |
final List<dynamic> first_error_value = errors_map.values.first; | |
final error_content = first_error_value.first; | |
throw("$error_content"); | |
case 3: | |
default: | |
throw("something_went_wrong_text"); | |
} | |
} | |
on DioError catch(e){ | |
throw(DioExceptions.fromDioError(e)); | |
} | |
on SocketException catch(e){ | |
throw("data_connection_text"); | |
} | |
} | |
/// retrieve list of ward | |
LocationInfo defaultWardOption = LocationInfo(id: 0, name: 'Select Ward', code: 0); | |
List<LocationInfo> wardList = [LocationInfo(id: 0, name: 'Select Ward', code: 0)]; | |
String wardId = '0'; | |
Future<List<LocationInfo>> retrieveWardList() async{ | |
var url = "/wards/$subCountyId"; | |
BaseOptions options = BaseOptions( | |
baseUrl: "$locationUrl", | |
contentType: "application/json", | |
receiveDataWhenStatusError: true, | |
sendTimeout: DURATION_TIMEOUT, | |
connectTimeout: DURATION_TIMEOUT, | |
receiveTimeout: DURATION_TIMEOUT, | |
// headers: {"Authorization" : "Bearer $token"} | |
); | |
Dio dio = Dio(options); | |
try{ | |
final response = await dio.get(url); | |
int responseValue = response.data['response_code']; | |
switch(responseValue){ | |
case 1 : | |
List<LocationInfo> wardsList = List<LocationInfo>.from(response.data['data'].map((data) => LocationInfo.fromJson(data))); | |
setState(() { | |
wardList = [defaultWardOption, ...wardsList]; | |
}); | |
return wardList; | |
case 2: | |
final Map<String, dynamic> errors_map = response.data['errors']; | |
final List<dynamic> first_error_value = errors_map.values.first; | |
final error_content = first_error_value.first; | |
throw("$error_content"); | |
case 3: | |
default: | |
throw("something_went_wrong_text"); | |
} | |
} | |
on DioError catch(e){ | |
throw(DioExceptions.fromDioError(e)); | |
} | |
on SocketException catch(e){ | |
throw("data_connection_text"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment