Home > Mobile >  How to get containers width when using a loop or List.generate?
How to get containers width when using a loop or List.generate?

Time:09-23

I am generating individual letters of a word into their own containers and I need to get the width of each container and add them to a list. How do I go about achieving this?

For example, if the word is "character" then flutter will render: [c][h][a][r][a][c][t][e][r]

Initially, I was using GlobalKeys to retrieve the width however, since I split the code into multiple files, I couldn't figure out how to access the GlobalKeys from another file and I can't find any information on google how to do that. Also, if the word has 20 letters then I will need to declare 20 GlobalKeys and a map to store those 20 keys.

I figure it would be better if there was a way to retrieve each container's width and store them in a list as they are being generated.

String displayWord = "character";

final [key0 to key19] = GlobalKey(); //PREVIOUS APPROACH
Map keys = { ** map of 20 keys ** }; //PREVIOUS APPROACH
.
.
.
    return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: List.generate(displayWord.length, (index) {
          return Container(
            key: keys[index], //PREVIOUS APPROACH
            child: Text(displayWord[index]),
          );
        }));

CodePudding user response:

I have done something similar with the help of the answer over here: https://stackoverflow.com/a/62536187/679553

You can use that code to calculate the size of text with a certain style.

CodePudding user response:

If you prefer using GlobalKey:

  static const letter = 'character';
  static final keys = List.generate(letter.length, (_) => GlobalKey());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Row(
          children: List.generate(
            letter.length,
            (index) {
              final key = keys[index];
              return Container(
                key: key,
                child: () {
                  final char = letter[index];
                  Future.delayed(Duration.zero, () {
                    final width =
                        (key.currentContext?.findRenderObject() as RenderBox)
                            .size
                            .width;
                    print('$char: $width');
                  });

                  return Text(char);
                }(),
              );
            },
          ),
        ),
      ),
    );
  }
  • Related