简体   繁体   中英

Flutter - How to get width of a FlatButton in a horizontal ListView

I want to get the width of a FlatButton in an horizontal ListView but i only can get Width: Infinity .

I can get width in an isolated FlatButton succesfully, but when the FlatButton is inside of a ListView i cannot, but i don't know why. Could you help me to get the width of a FlatButton when it is inside a ListView?

Thanks.

@override
  Widget build(BuildContext context) {


    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter App'),
      ),
      body: Container(
        height: 70.0,
        child: ListView(
          scrollDirection: Axis.horizontal,
          children: <Widget>[
            _flatButtonStoreWidth(),
            _flatButtonStoreWidth(),
            _flatButtonStoreWidth(),
            _flatButtonStoreWidth(),
            _flatButtonStoreWidth(),

          ],
        ),
      ),
    );
  }

Widget _flatButtonStoreWidth (){

return FlatButton (
  child: LayoutBuilder(
    builder: (BuildContext context, BoxConstraints constraints) {
      double _width = constraints.maxWidth;
      print('Width: $_width');
      return Text('This is a FlatButton');
    },
  ),
  onPressed: (){},
);

}

That's because the ListView with a horizontal axis has an infinite width. You'll have to provide a width for each FlatButton.

FlatButton gets its size from the parent. In this case the parent provides an infinite width. Therefore you should size the button yourself

To get width of the object in ListView you are supposed to:

  1. Give widget a GlobalKey .
  2. When build is complete, access the context through the GlobalKey .
  3. Using context you can get size by context.size .
  4. You can get width from Size object.

Following is the working code for your reference:

Widget _flatButtonStoreWidth() {
    GlobalKey globalKey = GlobalKey();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      double _width = globalKey.currentContext.size.width;
      print('Width: $_width');
    });
    return FlatButton(
      key: globalKey,
      child: Text('This is a FlatButton'),
      onPressed: () {},
    );
  }

I hope this helps, in case of any doubt please comment. In case this this answer helps you please accept and up-vote it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM