flutter 使行中的元素保持间距,如果它们太大,则将它们 Package 起来

uubf1zoe  于 2023-05-08  发布在  Flutter
关注(0)|答案(1)|浏览(72)

我想让元素停留在空间之间,如果他们不溢出,但如果他们 Package 他们。
这是我的代码:

return LayoutBuilder(
    builder: (BuildContext context, BoxConstraints constraints) {
      if (constraints.maxWidth <= MediaQuery.of(context).size.width * 0.5) {
        return Wrap(
          children: [
            Text("very long text"),
            Text("2"),
          ],
        );
      } else {
        return Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween
          children: [
            Text("short text"),
            Text("2"),
          ],
        );
      }
    },
  );

即使文本很小,它也总是进入自动换行

km0tfn4u

km0tfn4u1#

使用alignment: WrapAlignment.spaceBetween

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Wrap(
          alignment: WrapAlignment.spaceBetween,
          children: [
            Text('very long text'),
            Text("another text"),
          ],
        ),
        SizedBox(height: 16),
        Wrap(
          alignment: WrapAlignment.spaceBetween,
          children: [
            Text('verylongtext' * 3),
            Text("another text"),
          ],
        ),
      ],
    );
  }
}

相关问题