Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add items to a custom list in Flutter?

Tags:

flutter

I know to add an integer to an integer list is:

List<int> myList = [];
myList.add(1);

I know to add a string to a string list is:

List<String> myList = [];
myList.add("Hello World");

But how do I add a set to my custom list?

Class MyList {
  String name;
  int price;

MyList({
  this.name,
  this.price,
 });
}

I want myList to be something like this at the end:

List<MyList> myList = [
  MyList(
    name: 'Chorizo Canapes',
    price: 12.99,
  ),
  MyList(
    name: 'Cucumber',
    price: 8.99,
  ),
  MyList(
    name: 'Eggs',
    price: 11.99,
  ),
];

Thanks in advance.

EDIT: Sorry I didn't make myself clear. I want to do something like this:

List<MyList> myList = [];
myList.add({name: 'patato', price: 10})

How do I do this?

like image 974
57659 Avatar asked Mar 03 '23 00:03

57659


1 Answers

So what's problem? You can create this class and you can create this list. Exactly what you want.

Just note:

  1. Rewrite "Class" => "class"
  2. Change "price" from int to double (like Richard Heap said)
  3. Don't forget to import your classes file into file where you creating list like this: 'import 'package:project/myList.dart';'

Working code:

class MyList {
  String name;
  double price;

MyList({
  this.name,
  this.price,
 });
}

List<MyList> myList = [
  MyList(
    name: 'Chorizo Canapes',
    price: 12.99,
  ),
  MyList(
    name: 'Cucumber',
    price: 8.99,
  ),
  MyList(
    name: 'Eggs',
    price: 11.99,
  ),
];

Upd: Also you can mark parameter in class constructor as "@required" (with adding "import 'package:flutter/widgets.dart';") to make this parameter definitely required.

Example:

import 'package:flutter/widgets.dart';

class MyList {
  String name;
  double price;

MyList({
  @required this.name,
  this.price,
 });
}

List<MyList> myList = [
  MyList(
    name: 'Chorizo Canapes',
    price: 12.99,
  ),
  MyList(//Error: need parameter "name"
    price: 8.99,
  ),
  MyList(
    name: 'Eggs',
    price: 11.99,
  ),
];

Upd2: To create your own lists you can write

    List<MyList> myList2 = List<MyList>();
    myList2.add(
      MyList(
        name: 'Chorizo Canapes',
        price: 12.99,
      ),
    );

or

    List<MyList> myList3 = [];
    myList3.add(
      MyList(
        name: 'Cucumber',
        price: 8.99,
      ),
    );
like image 120
Alexander Seednov Avatar answered May 30 '23 06:05

Alexander Seednov