Flutter中如何为Wrap组件内最后两个元素设置space-between间距
问题根源
承载bbbb、cccc的右侧容器没有占满横向剩余可用宽度,spaceBetween属性仅在父容器有确定的额外可分配空间时才会生效,你当前的写法中右侧容器宽度是内容自适应,没有多余空间可分配,所以间距不生效。
实现方案
- 把每行外层的
Wrap替换为Row,更适配当前不需要换行的横向布局场景 - 给右侧承载
bbbb、cccc的Flex外层套Expanded,让它自动填充Row内除左侧Part标签外的所有剩余宽度 - 给右侧
Flex添加mainAxisAlignment: MainAxisAlignment.spaceBetween属性
修改后完整代码
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Column( children: [ // Part1 修改后 SizedBox( width: double.infinity, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( color: Colors.red, child: const Text('Part 1'), ), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( color: Colors.blue, child: const Text('bbbbbbbb'), ), Container(color: Colors.green, child: const Text('cccccccc')), ], ), ), ], ), ), // Part2 修改后 SizedBox( width: double.infinity, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( color: Colors.red, child: const Text('Part 2'), ), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Flexible( child: Container( color: Colors.blue, child: const Text( 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'), ), ), Container(color: Colors.green, child: const Text('cccccccc')), ], ), ), ], ), ), // Part3 修改后 SizedBox( width: double.infinity, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( color: Colors.red, child: const Text('Part 3'), ), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Flexible( child: Container( color: Colors.blue, child: const Text('bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'), ), ), Container(color: Colors.green, child: const Text('cccccccc')), ], ), ), ], ), ), ], ), ), ); } }
效果参考

内容的提问来源于stack exchange,提问作者Ccc
相关产品推荐
相关产品推荐

