Трепещущие кнопки с несколькими центрированными плавающими действиями

#flutter #dart #flutter-layout #flutter-dependencies

#флаттер #дротик #флаттер-макет #флаттер-зависимости

Вопрос:

Я попытался создать горизонтальные кнопки с несколькими плавающими действиями в нижней центральной позиции, но мои кнопки не центрированы в моем случае. Как я могу центрировать свои кнопки?

Вот демонстрация DartPad

Код

 import 'package:flutter/material.dart';

void main() => runApp(MyApp());

/// This is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter multiple centered floating action buttons';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: MyStatelessWidget(),
    );
  }
}

/// This is the stateless widget that the main application instantiates.
class MyStatelessWidget extends StatelessWidget {
  MyStatelessWidget({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Floating Action Buttons'),
      ),
      body: Center(child: const Text('Multiple centered Floating Action Buttons')),
      floatingActionButton: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          FloatingActionButton(
            onPressed: null,
            child: Icon(Icons.add, color: Colors.white),
            backgroundColor: Colors.green,
            heroTag: 'mapZoomIn',
          ),
          FloatingActionButton(
            onPressed: null,
            child: Icon(Icons.remove, color: Colors.white),
            backgroundColor: Colors.green,
            heroTag: 'mapZoomOut',
          ),
          FloatingActionButton(
            onPressed: null,
            child: Icon(Icons.place, color: Colors.white),
            backgroundColor: Colors.green,
            heroTag: 'showUserLocation',
          ),
          FloatingActionButton(
            onPressed: null,
            child: Icon(Icons.home, color: Colors.white),
            backgroundColor: Colors.green,
            heroTag: 'mapGoToHome',
          ),
        ],
      ),
    );
  }
}
 

Скриншот

введите описание изображения здесь

Ответ №1:

добавьте этот параметр в scaffold

floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat

 import 'package:flutter/material.dart';

void main() => runApp(MyApp());

/// This is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter multiple centered floating action buttons';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: MyStatelessWidget(),
    );
  }
}

/// This is the stateless widget that the main application instantiates.
class MyStatelessWidget extends StatelessWidget {
  MyStatelessWidget({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Floating Action Buttons'),
      ),
      body: Center(child: const Text('Multiple centered Floating Action Buttons')),
      floatingActionButton: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          FloatingActionButton(
            onPressed: null,
            child: Icon(Icons.add, color: Colors.white),
            backgroundColor: Colors.green,
            heroTag: 'mapZoomIn',
          ),
          FloatingActionButton(
            onPressed: null,
            child: Icon(Icons.remove, color: Colors.white),
            backgroundColor: Colors.green,
            heroTag: 'mapZoomOut',
          ),
          FloatingActionButton(
            onPressed: null,
            child: Icon(Icons.place, color: Colors.white),
            backgroundColor: Colors.green,
            heroTag: 'showUserLocation',
          ),
          FloatingActionButton(
            onPressed: null,
            child: Icon(Icons.home, color: Colors.white),
            backgroundColor: Colors.green,
            heroTag: 'mapGoToHome',
          ),
        ],
      ),
   floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      
    );
  }
}
 

Ответ №2:

FloatingActionButton по умолчанию имеет правильное заполнение, поэтому в приведенном выше примере кнопки слегка сдвинуты вправо.

Как правило, a Row не следует передавать в floatingActionButton in Scaffold .

Возможным решением было бы использовать Stack с Positioned элементом для отображения кнопок, как описано ниже:

 import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';

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

class sel extends StatefulWidget {
  @override
  _selState createState() => _selState();
}

class _selState extends State<sel> {
  String _date = "Not set";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
            child: SingleChildScrollView(
                child: Column(children: <Widget>[
      Container(
        color: Colors.grey,
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height / 10,
        child: Center(
          child: Text(
            "Attendance",
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
          ),
        ),
      ),
      SizedBox(
        height: 30.0,
      ),
      Padding(
          padding: const EdgeInsets.all(16.0),
          child: Container(
            child: Column(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                RaisedButton(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(5.0)),
                  elevation: 4.0,
                  onPressed: () {
                    DatePicker.showDatePicker(context,
                        theme: DatePickerTheme(
                          containerHeight: 210.0,
                        ),
                        showTitleActions: true,
                        minTime: DateTime(2000, 1, 1),
                        maxTime: DateTime(2022, 12, 31), onConfirm: (date) {
                      print('confirm $date');
                      _date = '${date.year} - ${date.month} - ${date.day}';
                      setState(() {});
                    }, currentTime: DateTime.now(), locale: LocaleType.en);
                  },
                  child: Container(
                    alignment: Alignment.center,
                    height: 50.0,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            Container(
                              child: Row(
                                children: <Widget>[
                                  Icon(
                                    Icons.date_range,
                                    size: 18.0,
                                    color: Colors.teal,
                                  ),
                                  Text(
                                    " $_date",
                                    style: TextStyle(
                                        color: Colors.teal,
                                        fontWeight: FontWeight.bold,
                                        fontSize: 18.0),
                                  ),
                                ],
                              ),
                            )
                          ],
                        ),
                        Text(
                          "  Change",
                          style: TextStyle(
                              color: Colors.teal,
                              fontWeight: FontWeight.bold,
                              fontSize: 18.0),
                        ),
                      ],
                    ),
                  ),
                  color: Colors.white,
                ),
                SizedBox(
                  height: 20.0,
                ),
              ],
            ),
          ))
    ]))));
  }
}
 

Который отображается следующим образом:
Плавающие кнопки действий