I have a vertical list of widgets to show and I want the very last one (a TextButton) to be aligned to the right of the screen. Normally, this can easily be achieved with CrossAxisAlignment.end in a Column, but I need it to be scrollable so I am using ListView. Children in ListView seem to always be automatically centered, but I want this last widget to be aligned to the right. How can I achieve this?
What I want: The TextButton is aligned to the right (this picture was done using a Column):
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
const ListTile(title: Text('Title'), subtitle: Text('Subtitle')),
const ListTile(title: Text('Title'), subtitle: Text('Subtitle')),
const ListTile(title: Text('Title'), subtitle: Text('Subtitle')),
TextButton(child: const Text('Tap me'), onPressed: (){}),
])
What I currently get using a ListView:
ListView(
children: [
const ListTile(title: Text('Title'), subtitle: Text('Subtitle')),
const ListTile(title: Text('Title'), subtitle: Text('Subtitle')),
const ListTile(title: Text('Title'), subtitle: Text('Subtitle')),
TextButton(child: const Text('Tap me'), onPressed: (){}),
]
CodePudding user response:
You can set the ButtonStyle attribute in Flutter buttons to modify alignment of children:
ListView(
children: [
const ListTile(title: Text('Title'), subtitle: Text('Subtitle')),
const ListTile(title: Text('Title'), subtitle: Text('Subtitle')),
const ListTile(title: Text('Title'), subtitle: Text('Subtitle')),
TextButton(
child: const Text('Tap me'),
onPressed: (){},
style: ButtonStyle(
alignment: Alignment.centerRight
),
),
],
),
),
CodePudding user response:
Wrap your widget Align( alignment: Alignment.centerRight,
body: ListView(
children: [
const ListTile(title: Text('Title'), subtitle: Text('Subtitle')),
const ListTile(title: Text('Title'), subtitle: Text('Subtitle')),
const ListTile(title: Text('Title'), subtitle: Text('Subtitle')),
Align(
alignment: Alignment.centerRight,
child: TextButton(child: const Text('Tap me'), onPressed: () {})),
],
)
More about Align
CodePudding user response:
Wrap the TextButton in a Row and set the Row's mainAxisAlignment to end. This should make the TextButton aligned to the right as you want.
ListView(
children: [
const ListTile(title: Text('Title'), subtitle: Text('Subtitle')),
const ListTile(title: Text('Title'), subtitle: Text('Subtitle')),
const ListTile(title: Text('Title'), subtitle: Text('Subtitle')),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [TextButton(child: const Text('Tap me'), onPressed: (){})],
),
],
),


