I’m building a Flutter app where users can edit their profile information. The profile form includes dropdowns for selecting the country and city. The list of countries is loaded into memory along with their respective cities. However, when a user edits their profile, I’m facing an issue with initializing the city dropdown with the user’s saved city.
class ProfilePage extends ConsumerStatefulWidget {
const ProfilePage({Key? key}) : super(key: key);
@override
ConsumerState<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends ConsumerState<ProfilePage> {
final _formKey = GlobalKey<FormBuilderState>();
late AppUser? usr;
List<String> cities = [];
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
await _loadInitialData();
});
}
Future<void> _loadInitialData() async {
final countries = ref.read(countriesProvider).countries;
await ref.read(userProvider.notifier).getUserProfile().then((value) {
usr = ref.read(userProvider.select((value) => value.user));
final country = countries.byName(usr?.country ?? '');
_updateCities(country, usr?.city);
// Patch user data to the form
});
}
void _updateCities(Country? country, [String? savedCity]) {
if (country != null) {
setState(() {
cities = country.cities.names;
});
// Set initial city value
}
}
@override
Widget build(BuildContext context) {
// other code
CustomFormDropdown<String>(
title: "Country",
name: 'country',
values: countries.names,
onChanged: (value) {
final country = countries.byName(value ?? '');
_updateCities(country);
},
),
CustomFormDropdown<String>(
title: "City",
name: 'city',
values: selectedCountry.cities.names,
),
// Other form fields...
}
}
The problem I’m facing is that the city dropdown doesn’t show the user’s saved city as the initial value. This is because the list of cities is initially empty and is fetched asynchronously after the user data is loaded.
I’ve tried updating the city list based on the selected country and setting the initial city value, but it doesn’t seem to work as expected.
How can I properly initialize the city dropdown with the user’s saved city after fetching the data? Any help or suggestions would be greatly appreciated. Thank you!
Image 1
Image 2
Image 1:
This is when I am edit the form. Here Country
object contains List<City>
objects. When user select any country Cities values get. Using this cities values we can choose cities from the dropdown menu.
Image 2:
In this scenario, when users view or update their profile information, the country and city names retrieved from the cloud are used to set the initial values of the dropdown menus. However, since the city values are initially empty, the initial city value fails to match with the dropdown values, resulting in it not being displayed.