SearchBar.dart (2444B)
1 import 'package:flutter/foundation.dart'; 2 import 'package:flutter/material.dart'; 3 4 class SearchBar extends StatefulWidget { 5 final TextEditingController filterTextController; 6 final onTextChanged; 7 8 SearchBar({ 9 this.filterTextController, 10 this.onTextChanged, 11 Key key, 12 }) : super(key: key); 13 14 @override 15 SearchBarState createState() => SearchBarState(); 16 } 17 18 class SearchBarState extends State<SearchBar> { 19 String text; 20 21 @override 22 build(BuildContext context) { 23 return TextField( 24 controller: widget.filterTextController, 25 keyboardType: TextInputType.text, 26 maxLines: 1, 27 style: TextStyle( 28 color: Colors.blueGrey, 29 fontSize: 15, 30 fontWeight: FontWeight.w400, 31 fontStyle: FontStyle.normal, 32 letterSpacing: 0, 33 ), 34 onChanged: (String newText) { 35 setState(() { 36 text = newText; 37 }); 38 if (widget.onTextChanged != null) widget.onTextChanged(newText); 39 }, 40 decoration: InputDecoration( 41 fillColor: Color(0xffedf0f2), 42 border: OutlineInputBorder( 43 borderRadius: BorderRadius.circular(20), 44 borderSide: BorderSide( 45 width: 0, 46 style: BorderStyle.none, 47 ), 48 ), 49 filled: true, 50 contentPadding: EdgeInsets.all(11), 51 prefixIcon: Icon( 52 Icons.search, 53 color: Color(0xffedf0f2), 54 ), 55 suffixIcon: text != null && text != "" 56 ? IconButton( 57 icon: Icon( 58 Icons.cancel, 59 color: Colors.blueGrey, 60 ), 61 onPressed: () { 62 // workaround 63 // see https://github.com/flutter/flutter/issues/35848#issuecomment-527854562 64 WidgetsBinding.instance.addPostFrameCallback((_) { 65 widget.filterTextController.clear(); // clear text 66 FocusScope.of(context) 67 .requestFocus(FocusNode()); // hide keyboard 68 setState(() { 69 text = ""; 70 }); 71 }); 72 }, 73 ) 74 : null, 75 hintText: "Search", 76 hintStyle: TextStyle( 77 color: Colors.blueGrey, 78 fontSize: 15, 79 fontWeight: FontWeight.w400, 80 fontStyle: FontStyle.normal, 81 letterSpacing: 0, 82 ), 83 ), 84 ); 85 } 86 }