dart 在Flutter中单击按钮时,列项未居中

of1yzvn4  于 2023-11-14  发布在  Flutter
关注(0)|答案(1)|浏览(155)

我希望单击按钮时列项目不居中。使用SingleChildScrollView“MainAxisAlignment.center“和“CrossAxisAlignment.center“不起作用。

import 'package:flutter/material.dart';

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

class MainApp extends StatelessWidget {
   MainApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
           child: Center(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  ElevatedButton(
                    onPressed: () {},
                    child: const Text(
                      ' Center',
                    ),
                  ),
                  ElevatedButton(
                    onPressed: () {},
                    child: const Text(
                      ' Center 2',
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

字符串

ozxc1zmp

ozxc1zmp1#

首先,你需要使用StatefulWidget,你可以创建一个状态bool来控制位置。如果你需要更多的位置控制,试试Stack widget。

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

class MainApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool isCenter = false;
  @override
  Widget build(BuildContext context) {
    final body = SafeArea(
      child: SingleChildScrollView(
        child: Column(
          children: [
            ElevatedButton(
              onPressed: () {
                setState(() {
                  isCenter = true;
                });
              },
              child: const Text(
                ' Center',
              ),
            ),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  isCenter = false;
                });
              },
              child: const Text(
                'Not Center',
              ),
            ),
          ],
        ),
      ),
    );
    return Scaffold(
      body: isCenter
          ? Center(
              child: body,
            )
          : body,
    );
  }
}

字符串

相关问题