Как поместить searchBar в appBar - Flutter? - PullRequest
0 голосов
/ 23 марта 2020

У меня проблемы с размещением панели поиска в AppBar, сейчас моя панель поиска находится ниже моего AppBar, я пытался использовать другой Container в моем AppBar, но безуспешно.

Мой код:

class _HomePageState extends State<HomePage> {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home:Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(100.0),
        child: AppBar(
          iconTheme: IconThemeData(color: Color.fromRGBO(9, 133, 46, 100)),
            backgroundColor: Colors.white,
            actions: <Widget>[
              IconButton(
                icon: Icon(
                  Icons.shopping_cart,
                  color: Color.fromRGBO(9, 133, 46, 100),
                ),
                onPressed: (){
                  print('klikniete');
                },
              ),
            ],
        ),
      ),
      body: Builder(
          builder: (context) => Container(
            child: FutureBuilder(
              future: fetchOrders(),
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (_ordersForDisplay.length == null) {
                  return Container(
                    child: Center(child: Text("Ładowanie...")),
                  );
                } else {
                  return ListView.builder(
                    itemCount: _ordersForDisplay.length + 1,
                    itemBuilder: (BuildContext context, int index) {
                      return index == 0 ? _searchBar() : _listItem(index - 1);
                    },
                  );
                }
              },
            ),
          ),
        ), 
      )
    );
  }

_searchBar() {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: TextField(
        decoration: InputDecoration(
          hintText: 'Wyszukaj po mieście...'
        ),
        onChanged: (text) {
          text = text.toLowerCase();
          setState(() {
            _ordersForDisplay = _orders.where((note) {
              var noteTitle = note.city.toLowerCase();
              return noteTitle.contains(text);
            }).toList();
          });
        },
      ),
    );
  }



  _listItem(index) {
    return GestureDetector(
      onTap: () => Navigator.of(context).push(
        MaterialPageRoute(builder: (context) => DetailPage(item: _ordersForDisplay[index])),
      ),
      child: Card(
        child: Padding(
          padding: const EdgeInsets.only(
              top: 32.0, bottom: 32.0, left: 16.0, right: 16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                _ordersForDisplay[index].firstName,
                style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
              ),
              Text(
                _ordersForDisplay[index].lastName,
                style: TextStyle(
                  color: Colors.grey.shade600
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Я помещаю searchBar в мой appBar, используя title: _searchBar, затем я удаляю return index == 0 ? _searchBar() : _listItem(index - 1); и вставляю только return _listItem(index, context), но сейчас у меня есть ошибка: RangeError (index): Invalid value: Only valid value is 0: 1

Ответы [ 2 ]

0 голосов
/ 23 марта 2020

Вы ожидаете этого

enter image description here

ИЛИ это?

enter image description here

Код:

class CustomSearchBarDemo extends StatefulWidget {
  @override
  _CustomSearchBarDemoState createState() => _CustomSearchBarDemoState();
}

class _CustomSearchBarDemoState extends State<CustomSearchBarDemo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,
        backgroundColor: Colors.white,
        title: Text("Search",style: TextStyle(color: Colors.black),),
        centerTitle: true,
        bottom: PreferredSize(
        preferredSize: Size.fromHeight(kToolbarHeight),
         child: Container(
          //  padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),   
            color: Colors.grey[300],
          ),
          child: Padding(
            padding: const EdgeInsets.all(5.0),
            child: Material(
              color: Colors.grey[300],
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Icon(Icons.search,color: Colors.grey),
                  Expanded(
                    child: TextField(
                      // textAlign: TextAlign.center,
                      decoration: InputDecoration.collapsed(
                        hintText: ' Search by name or address',
                      ),
                      onChanged: (value) {

                      },
                    ),
                  ),
                  InkWell(
                    child: Icon(Icons.mic,color: Colors.grey,),
                    onTap: () {

                    },
                  )
                ],
              ),
            ),
          )
        ) ,
      ),

      ),

    );
  }
}

ИЛИ

class CustomSearchBarDemo extends StatefulWidget {
  @override
  _CustomSearchBarDemoState createState() => _CustomSearchBarDemoState();
}

class _CustomSearchBarDemoState extends State<CustomSearchBarDemo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: 
      PreferredSize(
        preferredSize: Size.fromHeight(kToolbarHeight),
         child: Container(
          padding: const EdgeInsets.only(top:20),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),   
            color: Colors.grey[300],
          ),
          child: Padding(
            padding: const EdgeInsets.all(5.0),
            child: Material(
              color: Colors.grey[300],
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Icon(Icons.search,color: Colors.grey),
                  Expanded(
                    child: TextField(
                      // textAlign: TextAlign.center,
                      decoration: InputDecoration.collapsed(
                        hintText: ' Search by name or address',
                      ),
                      onChanged: (value) {

                      },
                    ),
                  ),
                  InkWell(
                    child: Icon(Icons.mic,color: Colors.grey,),
                    onTap: () {

                    },
                  )
                ],
              ),
            ),
          )
        ) ,
      ),

    );
  }
}
0 голосов
/ 23 марта 2020

Вы можете добавить любой виджет в свойство title панели приложений.

AppBar(
          title: TextField(
                    autofocus: true,
                    decoration: InputDecoration(
                      hintText: " Search...",
                      border: InputBorder.none,
                      suffixIcon: IconButton(icon:Icon(Icons.search), onPressed: () { 
                      },)
   ),
                    style: TextStyle(color: Colors.white, fontSize: 14.0),
                  ),
          iconTheme: IconThemeData(color: Color.fromRGBO(9, 133, 46, 100)),
            backgroundColor: Colors.white,
            actions: <Widget>[
              IconButton(
                icon: Icon(
                  Icons.shopping_cart,
                  color: Color.fromRGBO(9, 133, 46, 100),
                ),
                onPressed: (){
                  print('klikniete');
                },
              ),
            ],
        ),
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...