Home > Enterprise >  Converting List<int> to List<String> in flutter?
Converting List<int> to List<String> in flutter?

Time:09-09

I have a integar list like [1,2,3,4] and I a need to make a new list as a String list like ['1','2','3','4'], how can I convert it easily? I need to do this for using Sharedpreferences getStringList command.

List<int> selectedAmount = [];
IconButton(
   onPressed: () {
   Navigator.push(context,
   MaterialPageRoute(builder: (context) => BodyPage(goal: widget.goal)));
    waterAmount = amount[index];
    print(' secilen = $waterAmount');
    selectedAmount.add(waterAmount);
    setState(() => this.index = index);},
     icon: Icon(
     Icons.add,
     size: 28,
     color: Colors.blueGrey,))

and the other page:

  List<int> totalList = selectedAmount;


List<String> totalStringList = totalList.map((e) => e.toString()).toList();

"The instance member 'totalList' can't be accessed in an initializer." im getting this error.

CodePudding user response:

Easiest way to do so is

List<int> numbers = <int>[1,2,3,4];
  final List<String> strs = numbers.map((e) => e.toString()).toList();
  print(strs);

You can check the type of List in runtime by

print(strs.runtimeType);

CodePudding user response:

You can use map()

List<String> stringList = intList.map((element) => el.toString()).toList();

CodePudding user response:

To solve your issue whilst avoiding your issue, it's probably easiest to use:

List<String> get totalStringList => totalList.map((e) => e.toString()).toList();

This uses a getter, which does not have the same limitations as a normal variable.

Note that you won't be able to set (write to) this variable, but using it's value will work exactly the same as any other variable.

  • Related