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

前端 未结 2 509
北恋
北恋 2020-12-09 16:42

I am using a SliverAppBar in Flutter, with a background widget.

The thing is When it\'s expanded, the title and icons (leading and actions) should be wh

2条回答
  •  甜味超标
    2020-12-09 17:27

    You can use LayoutBuilder to get sliver AppBar biggest height. When biggest.height = 80.0, it actually means sliver appbar is collapsed.

    Here is a full example:

    import 'package:flutter/material.dart';
    
    void main() => runApp(MaterialApp(
          home: MyApp(),
        ));
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State {
      var top = 0.0;
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return [
              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 == 80.0 ? 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());
            },
          ),
        ));
      }
    }
    

    Final result:

提交回复
热议问题