Установить высоту фонового изображения, ширину, положение в флаттере - PullRequest
0 голосов
/ 27 января 2019

В моем SliverAppBar есть фоновое изображение. Я пробовал BoxFit.contain, BoxFit.fill ... и т. Д., Но ни один из них не работает для того, что я хотел бы сделать.

Вот что я могу получить:

not good

Но вот что я хочу:

good!

Я вижу, что есть BoxFit.values, но я не могу найти документацию, показывающую, как это использовать (если это правильно?)

Вот мой код:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:my_app/Theme.dart' as MyTheme;
import 'package:my_app/ui/rule_section_details/RuleRow.dart';

@override
class SliverHeaderTest extends StatelessWidget {
  final DocumentSnapshot ruleGroup;

  SliverHeaderTest(this.ruleGroup);

  @override
  Widget build(BuildContext context) {
    return Material(
      child: CustomScrollView(slivers: <Widget>[
        SliverAppBar(
          floating: true,
          backgroundColor: Color(int.parse(ruleGroup['color'])),
          expandedHeight: 200.0,
          flexibleSpace: FlexibleSpaceBar(
            // background: Image.asset('assets/img/circular-image.png',
            // fit: BoxFit.contain),
            background: new Image(
              image: new AssetImage(ruleGroup['image']),
              height: MyTheme.Dimens.ruleGroupListIconHeight,
              width: MyTheme.Dimens.ruleGroupListIconWidth,
            ),
            title: Text(ruleGroup['name'],
                style: MyTheme.TextStyles.ruleSectionPageTitle),
            centerTitle: true,
          ),
          actions: <Widget>[
            IconButton(
              icon: const Icon(Icons.share),
              tooltip: 'Share',
              onPressed: () {/* ... */},
            ),
          ],
        ),
        StreamBuilder(
            stream: Firestore.instance
                .collection('rules')
                .where("section", isEqualTo: ruleGroup['id'])
                .orderBy("subsection")
                .orderBy("subsubsection")
                .orderBy("subsubsubsection")
                .snapshots(),
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return SliverList(
                  delegate: SliverChildListDelegate(
                    [
                      Container(
                        child: new Center(child: new Text('Loading...')),
                      )
                    ],
                  ),
                );
              }
              return SliverPadding(
                  padding: EdgeInsets.only(top: 16.0),
                  sliver: SliverList(
                      delegate: SliverChildBuilderDelegate((context, index) {
                    return new RuleRow(snapshot.data.documents[index]);
                  }, childCount: snapshot.data.documents.length)));
            })
      ]),
    );
  }
}

1 Ответ

0 голосов
/ 01 февраля 2019

Это желаемое поведение background: свойства FlexibleSpaceBar - его Предположим, что он заполняет всю фоновую область Appbar, теперь title здесь не отдельный элемент для рендеринга ниже фона, а виджет переднего плана из FlexibleSpaceBar для отображения поверх background:

Если вам действительно нужно разделить заголовок и изображение, вы не можете использовать свойство background & title, но вместо этого вам нужно использовать Column или ListView вместо FlexibleSpaceBar.

Вы можете попробовать следующий код с возможными вариантами:

Рекомендуемое решение:

SliverAppBar(
            backgroundColor: Colors.blue,
            expandedHeight: 200.0,
            floating: true,
            //  pinned: true,
            flexibleSpace: FlexibleSpaceBar(
                centerTitle: true,
                title: Text("Collapsing Toolbar",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.0,
                    )),
                background: Row(
                  children: <Widget>[
                    Spacer(),
                    CircleAvatar(
                      radius: 54.0,
                      backgroundImage: NetworkImage(
                        "https://placeimg.com/640/480/animals",
                      ),
                    ),
                    Spacer(),
                  ],
                )),
          ),

Это изображение с radius: 68.0,.

enter image description here

Ниже приводятся фиксированные поля, может вызвать проблемы в адаптивном дизайне, но все еще работает.

С ClipOval:

SliverAppBar(
            backgroundColor: Colors.blue,
            expandedHeight: 200.0,
            floating: true,
            //  pinned: true,
            flexibleSpace: FlexibleSpaceBar(
                centerTitle: true,
                title: Text("Collapsing Toolbar",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.0,
                    )),
                background: Container(
                  margin:
                      EdgeInsets.symmetric(horizontal: 125.0, vertical: 50.0),
                  child: ClipOval(
                    child: Image.network(
                      "https://placeimg.com/640/480/animals",
                    ),
                  ),
                )),
          ),

enter image description here

с CircleAvatar

SliverAppBar(
            backgroundColor: Colors.blue,
            expandedHeight: 200.0,
            floating: true,
            //  pinned: true,
            flexibleSpace: FlexibleSpaceBar(
                centerTitle: true,
                title: Text("Collapsing Toolbar",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.0,
                    )),
                background: Container(
                  margin:
                      EdgeInsets.symmetric(horizontal: 125.0, vertical: 50.0),
                  child: CircleAvatar(
                    radius: 30.0,
                    backgroundImage: NetworkImage(
                      "https://placeimg.com/640/480/animals",
                    ),
                  ),
                )),
          ),

enter image description here

Обновление:

с ListView Опция. Примечание: AppBar высота определяется свойством expandedHeight: и не будет увеличиваться в случае увеличения радиуса изображения.

SliverAppBar(
            backgroundColor: Colors.blue,
            expandedHeight: 200.0,
            floating: true,
            //  pinned: true,
            flexibleSpace: Center(
              child: ListView(
                shrinkWrap: true,
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Spacer(),
                      CircleAvatar(
                        radius: 68.0,
                        backgroundImage: NetworkImage(
                          "https://placeimg.com/640/480/animals",
                        ),
                      ),
                      Spacer(),
                    ],
                  ),
                  Center(
                    child: Text("Collapsing Toolbar",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 22.0,
                        )),
                  ),
                ],
              ),
            ),
          ),
...