簡體   English   中英

Flutter 如何檢查 Sliver AppBar 是展開還是折疊?

[英]Flutter How to check if Sliver AppBar is expanded or collapsed?

我在 Flutter 中使用SliverAppBar ,帶有背景小部件。

問題是當它展開時,標題和圖標(引導和動作)應該是白色的以便正確看到,當它被折疊時,它們應該改為黑色

關於如何從中獲得布爾值的任何想法? 或解決此問題的其他方法。

謝謝你。

class SliverExample extends StatefulWidget {
  final Widget backgroundWidget;
  final Widget bodyWidgets;

  SliverExample({
    this.backgroundWidget,
    this.body,
  });
  @override
  _SliverExampleState createState() => _SliverExampleState();
}

class _SliverExampleState extends State<SliverExample> {

  // I need something like this
  // To determine if SliverAppBar is expanded or not.
  bool isAppBarExpanded = false;

  @override
  Widget build(BuildContext context) {

    // To change the item's color accordingly
    // To be used in multiple places in code
    Color itemColor = isAppBarExpanded ? Colors.white : Colors.black;

    // In my case PrimaryColor is white,
    // and the background widget is dark

    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            pinned: true,
            leading: BackButton(
              color: itemColor, // Here
            ),
            actions: <Widget>[
              IconButton(
                icon: Icon(
                  Icons.shopping_cart,
                  color: itemColor, // Here
                ),
                onPressed: () {},
              ),
            ],
            expandedHeight: 200.0,
            flexibleSpace: FlexibleSpaceBar(
              centerTitle: true,
              title: Text(
                'title',
                style: TextStyle(
                  fontSize: 18.0,
                  color: itemColor, // Here
                ),
              ),
              // Not affecting the question.              
              background: widget.backgroundWidget,
            ),
          ),
          // Not affecting the question.
          SliverToBoxAdapter(child: widget.body),
        ],
      ),
    );
  }
}

您可以使用 LayoutBuilder 來獲得 sliver AppBar 的最大高度。 當maximum.height = MediaQuery.of(context).padding.top + kToolbarHeight 時,其實就是sliver appbar 折疊了。

這是一個完整的例子,在這個例子中 MediaQuery.of(context).padding.top + kToolbarHeight = 80.0:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: MyApp(),
    ));

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var top = 0.0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: NestedScrollView(
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
        return <Widget>[
          SliverAppBar(
              expandedHeight: 200.0,
              floating: false,
              pinned: true,
              flexibleSpace: LayoutBuilder(
                  builder: (BuildContext context, BoxConstraints constraints) {
                // print('constraints=' + constraints.toString());
                top = constraints.biggest.height;
                return FlexibleSpaceBar(
                    centerTitle: true,
                    title: AnimatedOpacity(
                        duration: Duration(milliseconds: 300),
                        //opacity: top == MediaQuery.of(context).padding.top + kToolbarHeight ? 1.0 : 0.0,
                        opacity: 1.0,
                        child: Text(
                          top.toString(),
                          style: TextStyle(fontSize: 12.0),
                        )),
                    background: Image.network(
                      "https://images.unsplash.com/photo-1542601098-3adb3baeb1ec?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=5bb9a9747954cdd6eabe54e3688a407e&auto=format&fit=crop&w=500&q=60",
                      fit: BoxFit.cover,
                    ));
              })),
        ];
      },body: ListView.builder(
        itemCount: 100,
        itemBuilder: (context,index){
          return Text("List Item: " + index.toString());
        },
      ),
    ));
  }
}

最后結果:

在此處輸入圖像描述

需要使用 ScrollController 來達到想要的效果

試試這個代碼

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SliverExample(
        bodyWidgets: Text(
            'Hello Body gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg'),
        backgroundWidget: Text('Hello Background'),
      ),
    );
  }
}

class SliverExample extends StatefulWidget {
  final Widget backgroundWidget;
  final Widget bodyWidgets;

  SliverExample({
    this.backgroundWidget,
    this.bodyWidgets,
  });

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

class _SliverExampleState extends State<SliverExample> {

  ScrollController _scrollController;
  Color _theme ;

  @override
  void initState() {
    super.initState();
    _theme = Colors.black;

    _scrollController = ScrollController()
      ..addListener(
        () => _isAppBarExpanded ?
            _theme != Colors.white ?
        setState(
          () {
            _theme = Colors.white;
            print(
                'setState is called');
          },
        ):{}
            : _theme != Colors.black ?
        setState((){
          print(
              'setState is called');
          _theme = Colors.black;
        }):{},

      );
  }

  bool get _isAppBarExpanded {
    return _scrollController.hasClients &&
        _scrollController.offset > (200 - kToolbarHeight);
  }

  @override
  Widget build(BuildContext context) {
    // To change the item's color accordingly
    // To be used in multiple places in code
    //Color itemColor = isAppBarExpanded ? Colors.white : Colors.black;

    // In my case PrimaryColor is white,
    // and the background widget is dark

    return Scaffold(
      body: CustomScrollView(
        controller: _scrollController,
        slivers: <Widget>[
          SliverAppBar(
            pinned: true,
            leading: BackButton(
              color: _theme, // Here
            ),
            actions: <Widget>[
              IconButton(
                icon: Icon(
                  Icons.shopping_cart,
                  color: _theme, // Here
                ),
                onPressed: () {},
              ),
            ],
            expandedHeight: 200.0,
            flexibleSpace: FlexibleSpaceBar(
              centerTitle: true,
              title: Text(
                'title',
                style: TextStyle(
                  fontSize: 18.0,
                  color: _theme, // Here
                ),
              ),
              // Not affecting the question.
              background: widget.backgroundWidget,
            ),
          ),
          // Not affecting the question.
          SliverToBoxAdapter(child: widget.bodyWidgets),
        ],
      ),
    );
  }
}

如果你不熟悉? : 符號你可以使用以下

_scrollController = ScrollController()
      ..addListener(
          (){
            if(_isAppBarExpanded){
              if(_theme != Colors.white){
                setState(() {
                  _theme = Colors.white;
                  print('setState is called with white');
                });
              }
            }else{
              if(_theme != Colors.black){
                setState(() {
                  _theme = Colors.black;
                  print('setState is called with black');
                });
              }
            }
          }

使用具有 innerBoxIsScrolled 布爾標志的 NestedScrollView,這將是解決您的問題的一個不錯的解決方案,如下所示

NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          print("INNEER SCROLLED VI=======>$innerBoxIsScrolled");
          return <Widget>[
            SliverAppBar(), 
            ]},
body:Center(child:Text("Test IT")),

);

您可以使用SliverLayoutBuilder獲取當前的SliverConstraints並讀取其值,以輕松檢測發生了多少滾動。 這與LayoutBuilder非常相似,只是它在 sliver 世界中運行。

如果constraints.scrollOffset > 0 ,這意味着用戶至少滾動了一點。 使用這種方法,如果你想在滾動時做一些動畫/過渡,也很容易——只需獲取當前的scrollOffset並基於它生成你的動畫幀。

例如,當用戶滾動時,這個SliverAppBar會改變顏色:

  SliverLayoutBuilder(
    builder: (BuildContext context, constraints) {
      final scrolled = constraints.scrollOffset > 0;
      return SliverAppBar(
        title: Text('Sliver App Bar'),
        backgroundColor: scrolled ? Colors.blue : Colors.red,
        pinned: true,
      );
    },
  )

這對我有用檢查這條線

title: Text(title,style: TextStyle(color: innerBoxIsScrolled? Colors.black:Colors.white),),

將您的標題更改為

title: innerBoxIsScrolled? Text("hello world") : Text("Good Morning",)
class _ProductsState extends State<Products> {
  String image;
  String title;

  _ProductsState(this.image,this.title);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled){
          return <Widget>[
            SliverOverlapAbsorber(
              handle:
              NestedScrollView.sliverOverlapAbsorberHandleFor(context),
              sliver: SliverAppBar(
                leading: InkWell(
                  onTap: (){

                  },
                  child: Icon(
                    Icons.arrow_back_ios,
                    color: Colors.black,
                  ),
                ),
                backgroundColor: Colors.white,
                pinned: true,
                //floating: true,
                stretch: true,
                expandedHeight: 300.0,
                flexibleSpace: FlexibleSpaceBar(
                  centerTitle: true,
                  title: Text(title,style: TextStyle(color: innerBoxIsScrolled? Colors.black: Colors.white),),
                  background: CachedNetworkImage(imageUrl:image,fit: BoxFit.fitWidth,alignment: Alignment.topCenter,
                    placeholder: (context, url) => const CircularProgressIndicator(color: Colors.black,),
                    errorWidget: (context, url, error) => const Icon(Icons.error),),
                ),
              ),
            ),
          ];
        },
        body: Builder(
            builder:(BuildContext context) {
              return CustomScrollView(
                slivers: [
                  SliverOverlapInjector(
                    // This is the flip side of the SliverOverlapAbsorber above.
                    handle: NestedScrollView.sliverOverlapAbsorberHandleFor(
                        context),
                  ),
                  SliverToBoxAdapter(
                    child: Container(
                      height: 90,
                      color: Colors.black,
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: Container(
                      height: 200,
                      color: Colors.red,
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Container(
                        height: 200,
                        color: Colors.green,
                      ),
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: Container(
                      height: 200,
                      color: Colors.blue,
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: Container(
                      height: 200,
                      color: Colors.red,
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: Container(
                      height: 200,
                      color: Colors.blue,
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: Container(
                      height: 200,
                      color: Colors.red,
                    ),
                  ),
                ],
              );
            }
        ),
      ),
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM