Flutter: Giving equal width to two buttons in a Bu

2019-08-26 07:32发布

问题:

So here's my simple use case: I want to have two buttons next to each other horizontally. In native android (which is where I come from) I would have placed them in a LinearLayout and given them weight 1 each and setting their height to wrap_content.

Now, I have placed two RaisedButton in a ButtonBar widget but where I run the app I can see the second one is getting clipped. I want them to be equally spaced and have dynamic height as per their text. How can I achieve the same in flutter? Below is what I have tried so far:

import 'package:flutter/material.dart';

class NewScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
            automaticallyImplyLeading: true,
            title: Text("Building layouts"),
            leading: IconButton(
              icon: Icon(Icons.arrow_back),
              onPressed: () => Navigator.pop(context, false),
            )),
        body: myLayoutWidget(),
      ),
    );
  }
}

// replace this method with code in the examples below
Widget myLayoutWidget() {
  return Container(
    child: Column(
      children: <Widget>[
        ButtonBar(
          children: <Widget>[
            RaisedButton(
              onPressed: () {},
              child: Text("Very long text button",),
            ),
            RaisedButton(
              child: Text("Very very very very long text button"),
              color: Colors.red,
              onPressed: () {},
            )
          ],
        ),
      ],
    ),
  );
}

This is how it looks right now:

回答1:

Try using Row instead of Button Bar and add buttons to Expanded parent

Widget myLayoutWidget() {
  return Container(
    child: Row(

      children: <Widget>[
        Expanded(
          child: RaisedButton(
            onPressed: () {},
            child: Text("Very long text button",),
          ),
        ),
        Expanded(
          child: RaisedButton(
            child: Text("Very very very very long text button"),
            color: Colors.red,
            onPressed: () {},
          ),
        )
      ],
    ),
  );
}