Jani
Jani

Reputation: 406

Prevent SliverAppBar title from wrapping while it shrinks in Flutter

I have a Flutter app that uses a SliverAppBar in a CustomScrollView. The SliverAppBar's title is really long, so as the AppBar compresses on scrolling, the title starts to wrap several times.

I would like to prevent this behavior without using an overflow.
Note that the title can just "slide out", without being pinned at the top.

This allows for some possibilities, like:

GIF:

GIF demonstration

Code:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SafeArea(
        child: Scaffold(
          body: CustomScrollView(
            slivers: <Widget>[
              SliverAppBar(
                expandedHeight: 300,
                flexibleSpace: FlexibleSpaceBar(
                  background: Image.network(
                    'https://picsum.photos/500?grayscale&blur=2',
                    fit: BoxFit.cover,
                  ),
                  titlePadding: EdgeInsets.all(16),
                  title: Text(
                      'This is a very long title that will wrap several times while it shrinks'),
                ),
              ),
              SliverToBoxAdapter(
                child: Text(
                  '\nScrollable body:\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
                  style: TextStyle(fontSize: 30),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Upvotes: 2

Views: 2246

Answers (1)

Mobina
Mobina

Reputation: 7109

You can use a SizedBox wrapped inside a FittedBox:

title: FittedBox(
  child: SizedBox(
    width: MediaQuery.of(context).size.width,
    child: Center(
      child: Text(
        'This is a very long title that will wrap several times while it shrinks',
        style: TextStyle(fontSize: 30),
      ),
    ),
  ),
),

Result:

res

Upvotes: 4

Related Questions