Home > Software engineering >  Loop throw list of strings to create row and columns
Loop throw list of strings to create row and columns

Time:07-23

Hey guys i just started learning flutter recently and i ran into a problem i cant solve. Basically I have a list of numbers, always even number of numbers in list, and i want to place them in a row that has columns of 2 numbers one below the other. How can i do that? I want to look like this. Thanks for help.

I try

                Column(
                   children: [
                     for (var i = 0; result.length < i; i  )
                       Text(
                         result[i],
                       ),
                   ],
                 ),

I want to look like this

CodePudding user response:

use Map like this

class MyWidget extends StatelessWidget {

  final List<String> names;
  //or int whatever list you want

  const MyWidget(
      {Key? key,
   
      required this.names})
      : super(key: key);
  @override

  Widget build(BuildContext context) => Row(
    ///or Column
    children: names.map((e) => Text(e)).toList()
    //you can modify Text widget here also like adding styles or so
  );
}

CodePudding user response:

If I understand correctly, you want to make two rows, one above the other, that contain numbers and these two rows have the same length because your list has an even number of members?

If so, you can do it exactly as the statement.

class MyWidget extends StatelessWidget {

  final List<int> result;

  const MyWidget(
      {Key? key,
   
      required this.names})
      : super(key: key);
  @override

  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Row(
          children: list.getRange(0, range).map((e) => Text('$e')).toList(),
        ),
        Row(
          children: list.getRange(range, list.length).map((e) => Text('$e')).toList(),
        ),
      ]
    )
  }
}

So, you create a row with the first elements from 0 to the middle of your list, next you create a row from the middle to the end of your list. In the function getRange(start, end) "start" is inclusive and "end" is exclusive.

Alternatively, there is a Widget called Wrap that do the work of dividing your rows or columns whenever there is no space available. https://api.flutter.dev/flutter/widgets/Wrap-class.html

I recommend you the Flutter´s Youtube channel https://www.youtube.com/c/flutterdev for learning more about Widgets and TheFlutterWay to learn about layout and apps creation https://www.youtube.com/c/TheFlutterWay

  • Related