Flutter — Material Design 2 полупрозрачная панель приложений

Я хочу получить такой эффект: при прокрутке вверх панель приложений становится прозрачной, а под ней отображается список: < img src="https://i.stack.imgur.com/R2Hxr.png" alt="введите здесь описание изображения">

И прокрутил вниз, только белый цвет - первый элемент под панелью приложений:

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

Мой вид окна:

return Container(
      color: AppTheme.nearlyWhite,
      child: SafeArea(
        top: false,
        bottom: false,
        child: Scaffold(
          backgroundColor: AppTheme.nearlyWhite,
          body: Stack(
            children: <Widget>[
              DrawerUserController(
                screenIndex: _drawerIndex,
                drawerWidth: MediaQuery.of(context).size.width * 0.75,
                animationController: (AnimationController animationController) => _sliderAnimationController = animationController,
                onDrawerCall: (DrawerIndex drawerIndexdata) => _onDrawerCall(drawerIndexdata, _forceRefresh),
                onDrawerTap:(DrawerIndex drawerIndexdata) => _onDrawerTap(drawerIndexdata),

                screenView: Column(
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.fromLTRB(8, MediaQuery.of(context).padding.top + 8, 8, 8),
                      child: _createAppBar(),
                    ),
                    Expanded(
                        child:
                        Container(
                            color: Colors.white,
                            child: _screenView,
                        )
                    ),
                  ],
                ),
              ),
              new FabDialer(_fabMiniMenuItemList, Colors.blue, new Icon(Icons.add))
            ],
          ),
        ),
      ),
    );
  }

_screenView просто Listview().builder() и показывает InkWell виджет для каждого элемента. Моя панель приложений является пользовательской, определенной следующим образом:

_createAppBar() {
    return SizedBox(
      height: AppBar().preferredSize.height,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 8, left: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
            ),
          ),
          Expanded(
            child: Center(
              child: Padding(
                padding: const EdgeInsets.only(top: 4),
                child: Column(
                  children: <Widget>[
                    Text(
                      _menuSelected,
                      style: TextStyle(
                        fontSize: 22,
                        color: AppTheme.darkText,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                    Text(
                      globals.cityName,
                      style: TextStyle(
                        fontSize: 15,
                        color: AppTheme.darkerText,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 8, right: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
              color: Colors.white,
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  borderRadius:
                  BorderRadius.circular(AppBar().preferredSize.height),
                  child: Icon(Icons.refresh, color: AppTheme.dark_grey,),
                  onTap: () => setState(() => _forceRefresh = true),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

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

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

Итак, почти готово, но при прокрутке вниз панель приложений не будет прозрачной: введите здесь описание изображения

Я пытался возиться с настройкой фона панели приложений на цвет с прозрачностью, но безуспешно. Также мне нужно, чтобы мои виджеты на самом деле перекрывались (ListView должен перекрывать мою панель приложений), и он генерирует сообщения об ошибках от Flutter.

Любые идеи, как это сделать правильно?


person user1209216    schedule 04.02.2020    source источник
comment
Используйте непрозрачность для более четкого вывода   -  person A R    schedule 04.02.2020


Ответы (2)


установить extendBodyBehindAppBar: true в виджете Scaffold. Затем используйте виджет Opacity следующим образом:

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: Home()));
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(kToolbarHeight),
        child: Opacity( //Wrap your `AppBar`
          opacity: 0.8,
          child: AppBar(
            title: Text("Demo"),
          ),
        ),
      ),
      body: ListView.builder(
        itemCount: 30,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text("Tile: $index"),
          );
        },
      ),
    );
  }
}
person Crazy Lazy Cat    schedule 04.02.2020
comment
Это снова стандартная панель приложений, но мне нужно проверить, как она будет работать с моим пользовательским навигационным ящиком. - отредактировано, извините, только что понял, что вы имеете в виду, что я могу обернуть свою пользовательскую панель приложений таким образом. Я попробую. - person user1209216; 04.02.2020

 @override
  Widget build(BuildContext context) {
    return Container(
        child: Stack(
        children:[
          Container(
          color:Colors.white,
          padding:EdgeInsets.all(10),
          child:ListView.builder(
          itemCount:25+1,
            //length + 1 is beacause to show 1st item at the beginning
          shrinkWrap:true,
          itemBuilder:(con,ind){
            return ind==0 ?
              Container(height:70)
              :ListTile(
            title:Text('Item $ind',
                      style:TextStyle(color:Colors.black,))
            );
          }
          )
          ),
          Container(
          height:70,
          color:Colors.transparent,
          child:Card(
            color:Colors.white.withAlpha(80),
            child: Row(
            children:[
              Expanded(
                flex:1,
                child: IconButton(
                icon:Icon(Icons.list,color:Colors.black,size:25),
                onPressed:(){
                  //todo
                }
                ),
              ),
              Expanded(
                flex:3,
                child: Text('Title',
                           style:TextStyle(color:Colors.black,)),
              ),

              Expanded(
                flex:1,
                child: IconButton(
                icon:Icon(Icons.search,color:Colors.black,size:25),
                onPressed:(){
                  //todo
                }
                ),
              ),
              Expanded(
                flex:1,
                child: IconButton(
                icon:Icon(Icons.more_vert,color:Colors.black,size:25),
                onPressed:(){
                  //todo
                }
                ),
              )
            ]
            ),
          )
          )
        ]
        )
    );
  }

Скриншот

person Naveen Avidi    schedule 04.02.2020
comment
Вы можете прокручивать список, чтобы первый элемент списка не перекрывался? - person user1209216; 04.02.2020
comment
Если вы хотите увидеть элементы списка за панелью приложений, продолжайте мой ответ. Если вы не хотите видеть элементы за панелью приложения, замените Stack на Column - person Naveen Avidi; 04.02.2020
comment
Извините, вылетает с сообщением об ошибке [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: 'package:flutter/src/widgets/scroll_controller.dart': Failed assertion: line 170 pos 12: '_positions.isNotEmpty': - person user1209216; 04.02.2020
comment
Ошибка в вашем коде в _positions! Проверьте там! - person Naveen Avidi; 04.02.2020