SnackBar 不显示

Posted

技术标签:

【中文标题】SnackBar 不显示【英文标题】:SnackBar isn't displayed 【发布时间】:2020-05-16 16:05:55 【问题描述】:

我开发了一个用于选择和搜索项目的例程。一切正常,但没有显示 SnakBar。我不知道为什么。有人可以帮我吗?

这是带有 SnackBar 的代码:

      floatingActionButton: FloatingActionButton(
        onPressed: () async 
          if (response["result"] == "ok") 
            final snackBar = SnackBar(
              content: Text("Músicas adicionadas com sucesso"),
              duration: Duration(seconds: 2),
              action: SnackBarAction(
                label: 'Undo',
                onPressed: () 
                  // Some code to undo the change.
                ,
              ),
            );
        ,
        tooltip: 'Salvar Músicas',
        child: Icon(
          Icons.check,
        ),
        backgroundColor: Colors.orange,
      ),

这是完整的代码:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:mysongs_v2/global.dart';
import 'package:mysongs_v2/models/playlistsong.dart';
import 'package:mysongs_v2/models/song.dart';

class SelectSongScreen extends StatefulWidget 
  final int playlistId;
  final String playlistName;

  //constructor
  SelectSongScreen(this.playlistId, this.playlistName) : super();
  @override
  State<StatefulWidget> createState() 
    return _SelectSongScreenState();
  


class _SelectSongScreenState extends State<SelectSongScreen> 
  TextEditingController searchController = new TextEditingController();
  int userId = 1;
  var selectedSong = new Song();
  var songsSelected = new List<String>();
  var songsSelectedId = new List<String>();
  bool _isSelected = true;
  bool processing = false;
  bool isLoaded = false;

  onSearchTextChanged(String text) async 
    isLoaded = false;
    if (text.isEmpty) 
      setState(() );
      return;
    
    setState(() );
  

  Container _searchBar() 
    var _result = new Container(
      color: COLOR_MAIN,
      child: new Padding(
        padding:
            const EdgeInsets.only(top: 1.0, bottom: 1.0, left: 2.0, right: 2.0),
        child: new Card(
          child: new ListTile(
            leading: new Icon(Icons.search),
            title: new TextField(
              controller: searchController,
              decoration: new InputDecoration(
                  hintText: 'Search', border: InputBorder.none),
              onChanged: onSearchTextChanged,
            ),
            trailing: new IconButton(
              icon: new Icon(Icons.cancel),
              onPressed: () 
                searchController.clear();
                onSearchTextChanged('');
              ,
            ),
          ),
        ),
      ),
    );
    return _result;
  

  List<Container> _buildListItemsFromSongs(List<Song> songs) 
    int index = 0;
    return songs.map((song) 
      _isSelected = false;

      for (int i = 0; i <= this.songsSelected.length - 1; i++) 
        if (songsSelected[i] == song.name) 
          _isSelected = true;
        
      

      var _container = Container(
        child: Column(
          children: <Widget>[
            ListTile(
              selected: true,
              enabled: true,
              leading: _isSelected
                  ? Icon(
                      Icons.check,
                      size: 40,
                      color:
                          (_isSelected ? Colors.green[700] : Colors.green[500]),
                    )
                  : Icon(
                      Icons.add_circle,
                      size: 40,
                      color:
                          (_isSelected ? Colors.green[700] : Colors.green[500]),
                    ),
              title: Text(song.name,
                  style: TextStyle(
                      color: Colors.black, fontWeight: FontWeight.bold)),
              subtitle:
                  Text(song.singer, style: TextStyle(color: Colors.black)),
              onTap: () 
                isLoaded = true;
                print("You tapped to TILE $song.name");
                setState(() 
                  selectedSong = song;
                  var _pos = this.songsSelected.indexOf(song.name);
                  if (_pos == -1) 
                    this.songsSelected.add(song.name);
                   else 
                    this.songsSelected.removeAt(_pos);
                  
                  //processing = true;
                );
              ,
            ),
            new Divider(
              height: 20.0,
            )
          ],
        ),
      );
      index = index + 1;
      return _container;
    ).toList();
  

  @override
  Widget build(BuildContext context) 
    return new Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
          ),
          onPressed: () 
            Navigator.of(context).pop();
            Navigator.of(context).pop();
          ,
        ),
        backgroundColor: COLOR_MAIN,
        title: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text("Adicionar Músicas ao playist"),
            Text(
              widget.playlistName,
              style: TextStyle(fontSize: 16.0),
            )
          ],
        ),
      ),
      body: new FutureBuilder(
          future: searchSongsCheckPlaylist(http.Client(), widget.playlistId,
              searchController.text, isLoaded),
          builder: (BuildContext context, AsyncSnapshot<List> snapshot) 
            if (!snapshot.hasData) return new Container();

            List<Song> songs = new List();
            songs = snapshot.data;

            if (songs.length == 0 || songs[0].name.isEmpty) 
              return new Column(
                children: <Widget>[
                  _searchBar(),
                  new Expanded(
                    child: new ListView(
                      children: <Widget>[
                        Container(
                          //color: Colors.grey[500],
                          child: new Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: new Container(
                              child: new Icon(
                                Icons.search,
                                color: Colors.grey[500],
                                size: 260.0,
                                //semanticLabel: 'Text to announce in accessibility modes',
                              ),
                            ),
                          ),
                        ),
                        Container(
                          child: new Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Column(
                              children: <Widget>[
                                new Text(
                                  'Você pode pesquisar por nome da MÚSICA',
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 20.0,
                                      color: Colors.grey[500]),
                                ),
                                new Text(
                                  'ou por nome do ARTISTA',
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 20.0,
                                      color: Colors.grey[500]),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              );
             else 
              return new Column(
                children: <Widget>[
                  _searchBar(),
                  //Container(child: Icon(Icons.add),),
                  new Expanded(
                    child: ListView(
                      children: _buildListItemsFromSongs(songs),
                    ),
                  ),
                ],
              );
            
          ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async 
          if (response["result"] == "ok") 
            final snackBar = SnackBar(
              content: Text("Músicas adicionadas com sucesso"),
              duration: Duration(seconds: 2),
              action: SnackBarAction(
                label: 'Undo',
                onPressed: () 
                  // Some code to undo the change.
                ,
              ),
            );
        ,
        tooltip: 'Salvar Músicas',
        child: Icon(
          Icons.check,
        ),
        backgroundColor: Colors.orange,
      ),
    );
  


【问题讨论】:

【参考方案1】:

在 onPressed 中,您只需声明snackbar,但还需要调用showSnackBar(yourSnackBar),这是scaffoldState 上的一个方法。

所以你可以说 Scaffold.of(context).showSnackBar (yourSnackBar)

【讨论】:

【参考方案2】:

你必须从脚手架上得到小吃店

Scaffold.of(context).showSnackBar(
  SnackBar(
    content: Text('Snackbar'),
  ),
);

【讨论】:

【参考方案3】:

在您的代码中,您只需将SnackBar() 小部件设置为一个变量,并且永远不要在任何地方使用它。这不会显示它。

解决方案是将SnackBar()ScaffoldMessenger Widget 传递给showSnackBar() 方法。

示例:

ScaffoldMessenger.of(context).showSnackBar(mySnackBar);

要在视图中隐藏或删除它,请调用removeCurrentSnackBar() 方法,如下所示:

ScaffoldMessenger.of(context).removeCurrentSnackBar();

弃用说明

至于 2021,Scaffold.of(context) 在 Flutter v1.23.0-14.0.pre 之后被弃用,不应使用。

here 是我对相关问题的回答。

【讨论】:

以上是关于SnackBar 不显示的主要内容,如果未能解决你的问题,请参考以下文章

SnackBar 在 HTTPInterceptor 中使用时不显示

Flutter:使用barcode_scan插件后Snackbar不显示

Flutter SnackBar 在 Scaffold 中留下不可见的填充

扩展Snackbar 使其支持居中显示

如何在 Flutter 中正确显示 Snackbar?

在键盘上方显示 Android SnackBar?