Home > Software engineering >  How to receive a object list in flutter and user in CupertinoPicker Widget
How to receive a object list in flutter and user in CupertinoPicker Widget

Time:10-04

I wanna pass an object list into a CupertinoPicker but it only receive a String list how can i pass it?

how to receive this data Object and correctly treat to turn every child object into a object String, then i need to add every object name into a list of strings

import 'package:flutter/cupertino.dart';

class MainCupertinoPicker extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return _StateCupertinoPicker();
  }

}

class _StateCupertinoPicker extends State<MainCupertinoPicker>{

  int _selectedFruit = 0;
  // This shows a CupertinoModalPopup with a reasonable fixed height which hosts CupertinoPicker.
  void _showDialog(Widget child, {required Text}) {
    showCupertinoModalPopup<void>(
      context: context,
      builder: (BuildContext context) => Container(
        height: 216,
        padding: const EdgeInsets.only(top: 6.0),
        // The Bottom margin is provided to align the popup above the system navigation bar.
        margin: EdgeInsets.only(
          bottom: MediaQuery.of(context).viewInsets.bottom,
        ),
        // Provide a background color for the popup.
        color: CupertinoColors.systemBackground.resolveFrom(context),
        // Use a SafeArea widget to avoid system overlaps.
        child: SafeArea(
          top: false,
          child: child,
        ),
      )
    );
  }

  double _kItemExtent = 32.0;
  List<String> _fruitNames = <String>[
    'Crato',
    'Juazeiro',
    'Fortaleza'
  ];

  @override
  Widget build(BuildContext context) {
    return Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text(
                'Selecione o municipio: ',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold
                ),
              ),
              CupertinoButton(
                padding: EdgeInsets.zero,
                // Display a CupertinoPicker with list of fruits.
                onPressed: () => _showDialog(
                  CupertinoPicker(
                    magnification: 1.22,
                    squeeze: 1.2,
                    useMagnifier: true,
                    itemExtent: _kItemExtent,
                    // This is called when selected item is changed.
                    onSelectedItemChanged: (int selectedItem) {
                      setState(() {
                        _selectedFruit = selectedItem;
                        print(_selectedFruit);
                      });
                    },
                    children:
                        List<Widget>.generate(_fruitNames.length, (int index) {
                      return Center(
                        child: Text(
                          _fruitNames[index],
                        ),
                      );
                    }),
                  ), Text: null,
                ),
                // This displays the selected fruit name.
                child: Text(
                  _fruitNames[_selectedFruit],
                  style: const TextStyle(
                    fontSize: 22.0,
                  ),
                ),
              ),
            ],
          ),
    );
  }
}

I need to get the object string name add into _fruitNames list, then show to user the list, and when the user choose the name i need to return the complete object

This is the object that i wanna receive

class Tenant {
  int id;
  String name;
  String siafi;
  String url;
  String username;
  String password;
  String driverClassName;
  bool initialize;

  Tenant({required this.id, required this.name, required this.siafi, required this.url, required this.driverClassName, required this.username, required this.initialize, required this.password});

  factory Tenant.fromJson(Map<String, dynamic> json){
    return Tenant(
      id: json["id"], 
      name: json["name"], 
      siafi: json["siafi"], 
      url: json["url"], 
      driverClassName: json["driverClassName"], 
      username: json["username"], 
      initialize: json["initialize"], 
      password: json["password"]
    );
  }
}```

CodePudding user response:

Here is the modified code,

I have created list of objects, For simplification I create own object called Person

List<Person> personList = <Person>[Person(id:1, name:'Alan'), Person(id:2, name:'Ben'), Person(id:3, name:'Cat')];
// whereas
class Person{
  String name;
  int id;
  Person({required this.id, required this.name, });
  factory Person.fromJson(Map<String, dynamic> json){
    return Person(
      id: json["id"], 
      name: json["name"],
    );
  }
}

You can access the person name using personList[index].name. So that your code becomes

        CupertinoButton(
            padding: EdgeInsets.zero,
            // Display a CupertinoPicker with list of fruits.
            onPressed: () => _showDialog(
              CupertinoPicker(
                magnification: 1.22,
                squeeze: 1.2,
                useMagnifier: true,
                itemExtent: kItemExtent,
                // This is called when selected item is changed.
                onSelectedItemChanged: (int selectedItem) {
                  
                },
                children:
                    List<Widget>.generate(personList.length, (int index) {
                  return Center(
                    child: Text(
                      personList[index].name,
                    ),
                  );
                }),
              ),
              context,
              Text: null,
            ),
            // This displays the selected fruit name.
            child: Text(
              personList[_selectedFruit].name,
              style: const TextStyle(
                fontSize: 22.0,
              ),
            ),
          ),

You have a complete object in the list, you can select the object based on index value and return the entire object like this personList[selectedIndex]

CodePudding user response:

You don't need to create another list just for showing name of that object in CupertinoPicker you can use the same list and access the selected object with the help of _selectedfuit

You can achieve your expected behaviour with the help of code below:-

class MainCupertinoPicker extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _StateCupertinoPicker();
  }
}

class _StateCupertinoPicker extends State<MainCupertinoPicker> {
  int _selectedFruit = 0;
  // This shows a CupertinoModalPopup with a reasonable fixed height which hosts CupertinoPicker.
  void _showDialog(Widget child, {required Text}) {
    showCupertinoModalPopup<void>(
      context: context,
      builder: (BuildContext context) => Container(
        height: 216,
        padding: const EdgeInsets.only(top: 6.0),
        // The Bottom margin is provided to align the popup above the system navigation bar.
        margin: EdgeInsets.only(
          bottom: MediaQuery.of(context).viewInsets.bottom,
        ),
        // Provide a background color for the popup.
        color: CupertinoColors.systemBackground.resolveFrom(context),
        // Use a SafeArea widget to avoid system overlaps.
        child: SafeArea(
          top: false,
          child: child,
        ),
      ),
    );
  }

  final double _kItemExtent = 32.0;

  /// this is the the list of your your tenant object which may be static or may be coming from api as per your usecase
  List<Tenant> _tenants = [
  Tenant(
    id: 1,
    name: "Name 1",
    siafi: "Xyz",
    url: "Xyz",
    driverClassName: "Xyz",
    username: "Xyz",
    initialize: true,
    password: "Xyz",
  ),
  Tenant(
    id: 1,
    name: "Name 2",
    siafi: "Xyz",
    url: "Xyz",
    driverClassName: "Xyz",
    username: "Xyz",
    initialize: true,
    password: "Xyz",
  ),
  Tenant(
    id: 1,
    name: "Name 3",
    siafi: "Xyz",
    url: "Xyz",
    driverClassName: "Xyz",
    username: "Xyz",
    initialize: true,
    password: "Xyz",
  ),
  Tenant(
    id: 1,
    name: "Name 4",
    siafi: "Xyz",
    url: "Xyz",
    driverClassName: "Xyz",
    username: "Xyz",
    initialize: true,
    password: "Xyz",
  ),
  Tenant(
    id: 1,
    name: "Name 5",
    siafi: "Xyz",
    url: "Xyz",
    driverClassName: "Xyz",
    username: "Xyz",
    initialize: true,
    password: "Xyz",
  )
];


  /// no need to make another list for just showing modal popup
  // final List<String> _fruitNames = <String>['Crato', 'Juazeiro', 'Fortaleza'];

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          const Text(
            'Selecione o municipio: ',
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          ),
          CupertinoButton(
            padding: EdgeInsets.zero,
            // Display a CupertinoPicker with list of fruits.
            onPressed: () => _showDialog(
              CupertinoPicker(
                magnification: 1.22,
                squeeze: 1.2,
                useMagnifier: true,
                itemExtent: _kItemExtent,
                // This is called when selected item is changed.
                onSelectedItemChanged: (int selectedItem) {
                  setState(
                    () {
                      _selectedFruit = selectedItem;
                      if (kDebugMode) {
                        print(_tenants[_selectedFruit]);
                        print(_tenants[_selectedFruit].name);
                      }
                    },
                  );
                },
                children: List<Widget>.generate(
                  _tenants.length,
                  (int index) {
                    return Center(
                      child: Text(
                        _tenants[index].name,
                      ),
                    );
                  },
                ),
              ),
              Text: null,
            ),
            // This displays the selected fruit name.
            child: Text(
              _tenants[_selectedFruit].name,
              style: const TextStyle(
                fontSize: 22.0,
              ),
            ),
          ),
        ],
      ),
    );
  }
}


class Tenant {
  int id;
  String name;
  String siafi;
  String url;
  String username;
  String password;
  String driverClassName;
  bool initialize;

  Tenant(
      {required this.id,
      required this.name,
      required this.siafi,
      required this.url,
      required this.driverClassName,
      required this.username,
      required this.initialize,
      required this.password});

  factory Tenant.fromJson(Map<String, dynamic> json) {
    return Tenant(
        id: json["id"],
        name: json["name"],
        siafi: json["siafi"],
        url: json["url"],
        driverClassName: json["driverClassName"],
        username: json["username"],
        initialize: json["initialize"],
        password: json["password"]);
  }

  @override
  String toString() {
    return "id: $id, name: $name, siafi: $siafi, url: $url, driverClassName: $driverClassName, username: $username, initialize: $initialize, password: $password";
  }
}
  • Related