добавить непрозрачность всей странице, кроме одного виджета - PullRequest
0 голосов
/ 18 июня 2020

Как я могу применить непрозрачность ко всей странице, кроме IconButton в appbar во флаттере? Что-то вроде flutter_showcaseview

  @override
  Widget build(BuildContext context) {
    return Opacity(
      opacity: 0.5,
      child: Scaffold(
        appBar: AppBar(
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.add),
              onPressed: ...,
            ),
          ],
        ),
        body: ...
      ),
    );
  }

Любая помощь будет принята с благодарностью.

Ответы [ 2 ]

0 голосов
/ 18 июня 2020

Вот один из способов добиться такого подвига:

Строки, столбцы и гибкие элементы могут иметь Expanded дочернего элемента. Он получает коэффициент гибкости (который, согласно документации , определяет, «как гибкий дочерний элемент вписывается в доступное пространство»), и child самого себя.

Скажем, наш «настоящий» контент находится в вертикальном расположении, например Column. Тогда мы могли бы обернуть наш контент с помощью Stack (документация [здесь]) (https://api.flutter.dev/flutter/widgets/Stack-class.html), что позволяет нам добавлять контент выше исходного контента нашего приложения, и добавьте новый Column поверх него.

У него будет в основном два дочерних элемента Expanded и заполнитель. Заполнитель гарантирует, что один виджет не имеет непрозрачности, расположенной над ним, а дочерние элементы Expanded могут закрашивать остальную часть экрана непрозрачным цветом.

Вот код для иллюстрации идеи:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.symmetric(
          horizontal: 50.0,
        ),
        child: Stack(
          children: <Widget> [
            Column(
              children: <Widget>[
                Container(
                  height: 240.0,
                  color: Colors.red,
                ),
                Container(
                  height: 80.0,
                  width: double.infinity,
                  color: Colors.red,
                  child: Align(
                    alignment: Alignment.center,
                    child: Text("Your content here"),
                  ),
                ),
                Container(
                  height: 240.0,
                  color: Colors.red,
                )
              ],
            ),
            Column(
              children: <Widget>[
                Expanded(
                  child: Container(
                    color: Colors.black54,
                  ),
                ),
                Container(
                  height: 80.0
                ),
                Expanded(
                  child: Container(
                    color: Colors.black54,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
0 голосов
/ 18 июня 2020

Не могли бы вы сделать собственную панель приложений?
Я сделал образец. Надеюсь, это вам поможет.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Opacity Demo';
    return MaterialApp(
      title: appTitle,
      debugShowCheckedModeBanner: false,
      home: MyHomePage(title: appTitle),
    );
  }
}

// The StatefulWidget's job is to take data and create a State class.
// In this case, the widget takes a title, and creates a _MyHomePageState.
class MyHomePage extends StatefulWidget {
  final String title;

  MyHomePage({Key key, this.title}) : super(key: key);

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

// The State class is responsible for two things: holding some data you can
// update and building the UI using that data.
class _MyHomePageState extends State<MyHomePage> {
  // Whether the green box should be visible
  bool _visible = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
          preferredSize: Size.fromHeight(
            70,
          ),
        child: SafeArea(
          child: Container(
            height: 70,
            child: Stack(
              children: <Widget> [
                AnimatedOpacity(
                  opacity: _visible ? 1 : 0.2,
                  duration: Duration(milliseconds: 500),
                  child: AppBar(
                    title: Text('Title'),

                  ),
                ),
                Align(
                  alignment: Alignment.centerRight,
                  child: IconButton(
                        icon: Icon(Icons.add),
                        onPressed: () {}
                      ),
                  ),
              ]
            ),
          ),
        ),
        ),
      body: AnimatedOpacity(
          opacity: _visible ? 1 : 0.2,
          duration: Duration(milliseconds: 500),
          child: Center(
        child: Container(
            width: 200.0,
            height: 200.0,
            color: Colors.green,
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // Call setState. This tells Flutter to rebuild the
          // UI with the changes.
          setState(() {
            _visible = !_visible;
          });
        },
        tooltip: 'Toggle Opacity',
        child: Icon(Icons.flip),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
...