skip to Main Content

I am stuck in one problem. I have one dropdown which item are in form A-B, C-D, E-F, F-G all have their own id suppose if selected item in dropdown in A-B then how can we swap A-B to B-A.

import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:ev_passenger/models/main_route_model.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;

class DropdownItemsProvider with ChangeNotifier {
  List<RouteModel> _dropdowndItems = [];
  RouteModel? _selecteddItem;
  List<RouteModel> get dropdowndItems => _dropdowndItems;
  RouteModel? get selecteddItem => _selecteddItem;

  Map<int, String> _dropdownItems = {};

  int? _selectedItem;

  Map<int, String> get dropdownItems => _dropdownItems;
  int? get selectedItem => _selectedItem;
  final List<int> _selectedCategoryValue = [1];
  List<int> get selectedCategoryValue => _selectedCategoryValue;

  Map<int, String> _dropdownItemlt = {};

  int? _selectedItemlt;

  Map<int, String> get dropdownItemlt => _dropdownItemlt;
  int? get selectedItemlt => _selectedItemlt;
  Map<int, String> _dropdownItemlg = {};

  int? _selectedItemlg;

  Map<int, String> get dropdownItemlg => _dropdownItemlg;
  int? get selectedItemlg => _selectedItemlg;

  Map<int, String> _dropdownItemlt2 = {};

  int? _selectedItemlt2;

  Map<int, String> get dropdownItemlt2 => _dropdownItemlt2;
  int? get selectedItemlt2 => _selectedItemlt2;
  Map<int, String> _dropdownItemlg2 = {};

  int? _selectedItemlg2;

  Map<int, String> get dropdownItemlg2 => _dropdownItemlg2;
  int? get selectedItemlg2 => _selectedItemlg2;

  Map<int, String> _dropdownItemfrid = {};

  int? _selectedItemfrid;

  Map<int, String> get dropdownItemfrid => _dropdownItemfrid;
  int? get selectedItemfrid => _selectedItemfrid;

  Map<int, String> _dropdownItemtoid = {};

  int? _selectedItemtoid;

  Map<int, String> get dropdownItemtoid => _dropdownItemtoid;
  int? get selectedItemtoid => _selectedItemtoid;

  // Future<List<RouteModel>> fetchData() async {
  Future<void> fetchData() async {
    var prefs = await SharedPreferences.getInstance();
    var logtoken = prefs.getString("token_value");
    if (logtoken == null) {
      print("Token is null");
      return;
    }
    var tokenvaluee = logtoken!;
    var header = {'Authorization': 'Bearer $tokenvaluee'};
    final response = await http
        .get(Uri.parse('https://eyatayat.com/api/all-routes'), headers: header);

    if (response.statusCode == 200) {
      final List<dynamic> data = json.decode(response.body);

      // _dropdownItems = data.map((json) => RouteModel.fromJson(json)).toList();
      // print("Number of items: ${_dropdownItems.length}");
      // notifyListeners();
      // return _dropdownItems;
      _dropdownItems.clear();

      for (var item in data) {
        final route = RouteModel.fromJson(item);
        // _dropdownItems[route.id ?? 0] = route.from ?? '';
        _dropdownItems[route.id ?? 0] =
            '${route.from ?? ''}  -  ${route.to ?? ''}';

        _dropdownItemlt[route.id ?? 0] = '${route.fromLatitude ?? ''}';
        _dropdownItemlg[route.id ?? 0] = '${route.fromLongitude ?? ''}';
        _dropdownItemlt2[route.id ?? 0] = '${route.toLatitude ?? ''}';
        _dropdownItemlg2[route.id ?? 0] = '${route.toLongitude ?? ''}';
        _dropdownItemfrid[route.id ?? 0] = '${route.fromLocationId ?? ''}';
        _dropdownItemtoid[route.id ?? 0] = '${route.toLocationId ?? ''}';
      }

      _dropdowndItems = data.map((json) => RouteModel.fromJson(json)).toList();
      // Replace 'from' with the appropriate property

      print("Number of items: ${_dropdownItems.length}");
      notifyListeners();
    } else {
      print("API request failed with status code ${response.statusCode}");
      print("Response body: ${response.body}");
      // If the server did not return a 200 OK response, throw an exception
      throw Exception('Failed to load data');
    }
  }

  void selectItem(int? item) {
    _selectedItem = item;

    notifyListeners();
  }

  void selectdItem(RouteModel? item) {
    _selecteddItem = item;

    notifyListeners();
  }

  void getselectdItemlat(int? item) {
    _selectedItemlt = item;

    notifyListeners();
  }

  void getselectdItemlg(int? item) {
    _selectedItemlg = item;

    notifyListeners();
  }

  void getselectdItemlat2(int? item) {
    _selectedItemlt2 = item;

    notifyListeners();
  }

  void getselectdItemlg2(int? item) {
    _selectedItemlg2 = item;

    notifyListeners();
  }

  void getselectdItemfrId(int? item) {
    _selectedItemfrid = item;

    notifyListeners();
  }

  void getselectdItemtoId(int? item) {
    _selectedItemtoid = item;

    notifyListeners();
  }

  void swapFromTo() {
    if (_selectedItem != null) {
      final selectedRoute = _dropdowndItems[_selectedItem! - 1];

      final String from = selectedRoute.from ?? '';
      final String to = selectedRoute.to ?? '';

      selectedRoute.from = to;
      selectedRoute.to = from;

      // Update selecteddItem
      _selecteddItem = selectedRoute;
      print("${selectedRoute.from.toString()}-${selectedRoute.to.toString()}");
      _selectedItem = _dropdowndItems.indexOf(selectedRoute) + 1;
      selectdItem(selectedRoute);

      notifyListeners(); // Notify listeners to update the UI
    }
  }

  // void swapFromTo() {
  //   print(_selectedItem);
  //   if (_selectedItem != null) {
  //     final selectedRoute = _dropdowndItems[_selectedItem! - 1];
  //     final String from = selectedRoute.from ?? '';
  //     final String to = selectedRoute.to ?? '';

  //     selectedRoute.from = to;
  //     selectedRoute.to = from;

  //     // Update selecteddItem
  //     _selecteddItem = selectedRoute;
  //     print("${selectedRoute.from.toString()}-${selectedRoute.to.toString()}");
  //     _selectedItem = _dropdowndItems.indexOf(selectedRoute) + 1;

  //     _dropdowndItems[_selectedItem! - 1] = selectedRoute;

  //     // Update selecteddItem
  //     _selecteddItem = selectedRoute;

  //     notifyListeners(); // Notify listeners to update the UI
  //   }
  // }

  String buildSelectedRouteText(int selectedIndex) {
    if (selectedIndex >= 0 && selectedIndex < _dropdowndItems.length) {
      final selectedRoute = _dropdowndItems[selectedIndex];
      final from = selectedRoute.from ?? '';
      final to = selectedRoute.to ?? '';
      return '$from - $to';
    }
    return ''; // Handle out-of-bounds index or other error cases
  }

  int _selectedItemIndex = 0;

  int get selectedItemIndex => _selectedItemIndex;
  void selecttItem(int index) {
    _selectedItemIndex = index;
    notifyListeners();
  }

  RouteModel? _selectedItemed;
  RouteModel? get selecteddItemed => _selectedItemed;
  int? _selectedRouteId;
  void selectItemed(int? item) {
    try {
      _selectedItemed = _dropdowndItems.firstWhere((route) => route.id == item);
    } catch (e) {
      _selectedItemed = null; // Set it to null if no element is found
    }

    notifyListeners();
  }
}

This is my provider:

Consumer<DropdownItemsProvider>(
                      builder: (context, dropdownItemsProvider, child) {
                    final routeDataProvider =
                        Provider.of<DropdownItemsProvider>(context);
                    final selectedRoute = routeDataProvider.selectedItem;
                    print('anil');
                    print(selectedRoute);

                    final _listroutes = dropdownItemsProvider.dropdownItems;

                    return DropDownTextField(
                      textEditingController: _mainrouteController,
                      title: 'Route',
                      hint: 'Select your Route',
                      options: _listroutes,
                      selectedOptions: [_selectedRouteId ?? -1],
                      onChanged: (selectedRouteIds) {
                        if (selectedRouteIds!.isNotEmpty) {
                          dropdownItemsProvider.selectItem(selectedRouteIds[0]);

                          final dropdownSubProvider =
                              context.read<DropdownSubProvider>();
                          final dropdownSubProviders =
                              context.read<DropdownSubProviderss>();

                          // Get the selected item from the provider
                          final selectedRouteItem =
                              dropdownItemsProvider.selectedItem;
                          final selectedRoutefromId =
                              dropdownItemsProvider.selectedItemfrid;
                          final selectedRoutetoId =
                              dropdownItemsProvider.selectedItemtoid;
                          print(selectedRouteItem);

                          if (selectedRouteItem != null) {
                            // Access the 'id' property of the selected item
                            final selectedRouteId = selectedRouteItem;

                            // Use selectedRouteId in your fetchSubRoute and fetchSubRoutes methods
                            dropdownSubProvider.fetchSubRoute(
                                tokenvaluee,
                                selectedRouteId,
                                selectedRoutefromId.toString(),
                                selectedRoutetoId.toString());
                            dropdownSubProviders.fetchSubRoutes(
                                tokenvaluee,
                                selectedRouteId,
                                selectedRoutefromId.toString(),
                                selectedRoutetoId.toString());
                          }
                        }
                      },
                    );
                  }),
                ]),
              ),
            ),
          ),
          Consumer<DropdownItemsProvider>(
            builder: (context, dropdownItemsProvider, child) {
              final selectedRoute = dropdownItemsProvider.selectedItem;
              return FloatingActionButton(
                onPressed: () {
                  // Call the swapFromTo method from the provider
                  dropdownItemsProvider.swapFromTo();
                },
                child: const Icon(Icons.swap_horiz),
              );
            },
          ),

This is my dropdown:

Here in first dropdown selected item is nepalgunj -mahendranagar. I want to swap it to Mahendranagar-nepalgunj when swap icon is pressed

`

2

Answers


  1. import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      List<String> dropdownItems = ["A-B", "C-D", "E-F", "F-G"];
      String selectedItem = "A-B";
    
      void swapSelectedItem() {
        // Find the index of the selected item
        int selectedIndex = dropdownItems.indexOf(selectedItem);
    
        if (selectedIndex != -1) {
          // Split the selected item into two parts
          List<String> parts = selectedItem.split('-');
    
          // Swap the two parts
          String swappedItem = "${parts[1]}-${parts[0]}";
    
          // Update the data source
          dropdownItems[selectedIndex] = swappedItem;
    
          // Update the selected item
          selectedItem = swappedItem;
    
          // Trigger a rebuild to reflect the changes
          setState(() {});
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(debugShowCheckedModeBanner: false,
          home: Scaffold(
            appBar: AppBar(
              title: Text("Dropdown Swap Example"),
            ),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  DropdownButton<String>(
                    value: selectedItem,
                    items: dropdownItems.map((String item) {
                      return DropdownMenuItem<String>(
                        value: item,
                        child: Text(item),
                      );
                    }).toList(),
                    onChanged: (newValue) {
                      setState(() {
                        selectedItem = newValue!;
                      });
                    },
                  ),
                  SizedBox(height: 20),
                  ElevatedButton(
                    onPressed: () {
                      swapSelectedItem();
                    },
                    child: Text("Swap"),
                  ),
                ],
              ),
            ),
          ),
        );
      }
    }
    
    Login or Signup to reply.
  2. Take it easy and think a little bit deeper.

    make a var bool isSwap = false;

    setState(() { //add this to your sawp 
      isSwap = !isSwap; //you can use provider as well
    });
    

    Now, add conditions to your drawdown based on isSwap.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search