Выровнять центр виджета по нижнему краю AppBar - PullRequest
0 голосов
/ 27 апреля 2020

Мне нужно выровнять центр виджета по нижнему краю панели приложения. Таким образом, он будет расположен вертикально наполовину на панели приложений и наполовину на теле страницы.

Сейчас я добавил виджет в нижнюю часть AppBar, но он не будет совпадать с его горизонтальной центральной линией.

В настоящее время это выглядит так:

enter image description here

Пока я хочу, чтобы центр кнопки SelectEnvironment вместе с горизонтальным белым строка будет «сидеть» ровно на нижнем краю appBar

Код для appBar выглядит следующим образом:

  class CustomAppBar extends AppBar {

     final Widget appBarActionButton;

     CustomAppBar({Widget title = AppUtils.EMPTY_TEXT_VIEW, this.appBarActionButton}): super(
        title: title,
        backgroundColor: Colors.blueGrey,
        elevation: 0,
        bottom: PreferredSize(
            child: Stack( //The stack holds the horizontal line and the button aligned cente
              alignment: Alignment.center,
              children: <Widget>[
                Container( //This is the horizontal line
                  color: Colors.GeneralDividerGray,
                  height: 1.0,
                ),
                Align(
                  child: Container(
                      child: appBarActionButton, //This is the button widget
                      ),
               )
          ],
        ),
        preferredSize: Size.fromHeight(4.0)),
      );
 }

Если есть лучший способ добиться этого, вывести его за пределы appbar у меня все в порядке, пока он даст тот же эффект.

Ответы [ 2 ]

1 голос
/ 27 апреля 2020

Я думаю, вы должны использовать Stack и Column вот так

import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';

typedef void OnWidgetSizeChange(Size size);

class MeasureSize extends StatefulWidget {
  final Widget child;
  final OnWidgetSizeChange onChange;

  const MeasureSize({
    Key key,
    @required this.onChange,
    @required this.child,
  }) : super(key: key);

  @override
  _MeasureSizeState createState() => _MeasureSizeState();
}

class _MeasureSizeState extends State<MeasureSize> {
  @override
  Widget build(BuildContext context) {
    SchedulerBinding.instance.addPostFrameCallback(postFrameCallback);
    return Container(
      key: widgetKey,
      child: widget.child,
    );
  }

  var widgetKey = GlobalKey();
  var oldSize;

  void postFrameCallback(_) {
    var context = widgetKey.currentContext;
    if (context == null) return;

    var newSize = context.size;
    if (oldSize == newSize) return;

    oldSize = newSize;
    widget.onChange(newSize);
  }
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Size s;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Stack(
      children: [
        Column(
          children: [
            MeasureSize(
              onChange: (size) {
                setState(() {
                  s = size;
                });
              },
              child: AppBar(
                title: Text('title'),
              ),
            ),
            SizedBox(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height - (s?.height ?? 0.0),
                child: Center(child: Text('body')))
          ],
        ),
        Positioned(
          top: (s?.height ?? 0.0) - 16.0,
          child: Container(
            width: MediaQuery.of(context).size.width,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                    height: 32,
                    color: Colors.red[400],
                    padding: EdgeInsets.all(6),
                    child: Center(child: Text('Select Environment'))),
              ],
            ),
          ),
        )
      ],
    ));
  }
}

enter image description here

1 голос
/ 27 апреля 2020

Лучший способ - использовать Щепки через виджет, как показано ниже:

  ScrollController scrollController = new ScrollController();
  return Stack(
    children: [
      NestedScrollView(
        controller: scrollController,
        headerSliverBuilder: (context, value){
          return [
//            list of widgets in here
          ];
        },
        body: Container(
          // here, your normal body goes
        ),
      ),
      Positioned(
        top: 50.0,
        left: 100.0,
        child: Container(
          // your centered widget here
        ),
      )
    ]
  );
}

Вместо использования обычной панели приложений, вы должны использовать SliverAppBar

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...