How to bring back the status bar when textfiled is tap? - dart

I have implemented
SystemChrome.setEnabledSystemUIOverlays([]);
in my main function to hide the status bar but I need to bring it back when I tap on my Textfield. So the user can use the back option on the bottom bar.
I've tried to do this :
onTap: () => SystemChrome.restoreSystemUIOverlays()
but that don't work.
Container _getSearchBar() {
return new Container(
margin: const EdgeInsets.only(top: 21.0, right: 8.0, left: 8.0),
child: new Card(
child: new ListTile(
leading: new Icon(Icons.search),
title: new TextField(
onTap: () => SystemChrome.restoreSystemUIOverlays(),
controller: controller,
decoration: new InputDecoration(
hintText: 'Search', border: InputBorder.none),
),
trailing: new IconButton(
icon: new Icon(Icons.cancel),
onPressed: () {
controller.clear();
},
),
),
),
);
}

According to restoreSystemUIOverlays() function documentation it only returns the last setting of setEnabledSystemUIOverlays() which is in your case hiding status bar. Instead you should use :
onTap: () => SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);

Related

How do I make the global type context variable in flutter?

I just figured out some problem when I tried to navigate from one page to the other in flutter. The Navigation.push method requires the context variable and I need reference to the context for navigating.
Widget navBox(Color aColor, double left, double top, Icon icon,String action, Route route) {
return Positioned (
left: left,
top: top,
child: InkWell(
borderRadius: BorderRadius.circular(30.0),
onTap: () {
Navigator.push(context, route);
},
child: new Container(
height: 220.0,
width: 220.0,
decoration: BoxDecoration(
color: aColor,
borderRadius: BorderRadius.circular(30.0),
),
child: Padding(
padding: EdgeInsets.all(40.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
icon,
new Text(action, style: TextStyle(color: Colors.white, fontSize: 20.0, fontFamily: 'Oxygen')),
],
),
),
),
),
);
}
I expected to navigate to the other page by the call of this function with proper route defined.
I got the error like:
The following NoSuchMethodError was thrown while handling a gesture
The method 'ancestorStateOfType' was called on null.
Just add a context parameter to the method's signature. But also have in mind that methods shouldn't have so many parameters, because it makes them harder to use.
Wrapping the InkWell with the new Builder or the Material widget solves the problem.
Here's the snippet on how I solved the problem:
child: new Container(
height: 220.0,
width: 220.0,
decoration: BoxDecoration(
color: aColor,
borderRadius: BorderRadius.circular(30.0),
),
child: new Builder(
builder: (context) => InkWell(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => GetData()),);
},
child: Padding(
padding: EdgeInsets.all(40.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
icon,
new Text(action, style: TextStyle(color: Colors.white, fontSize: 20.0, fontFamily: 'Oxygen')),
],
),
),
),
),
),
I am only listing the Container widget of the function. So rest of them could be figured out by yourself.

Flutter - Detect TexField on tap

I maked a flutter app in windows and all works, but when i tried to compile to iOS throw a unexpected error. In the Textfield detects that the 'onTap' isn´t a a correct parameter. I don´t know what happens, in windows doesn´t return this error. Anyway. anybody know how fix this and what is the correct way to detect 'onTap' on texfield?
new Container(
color: Colors.blue[300],
child: new Padding(
padding: const EdgeInsets.all(8.0),
child: new Card(
child: new ListTile(
leading: new Icon(Icons.search),
title: new TextField(
onTap: () { <--- The named parameter 'onTap' isn´t defined
Navigator.push(
context,
UPDATE
I tried this but doesn´t work
title: new GestureDetector(
child: new TextField(
controller: searchController,
decoration: new InputDecoration(
hintText: 'Buscar parcela', border: InputBorder.none),
)),
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => new EstatesPage(
parcela: widget.parcela,
dropdownItem: dropdownSelection)));
},
UPDATE 2: SOLUTION
I updated flutter and brew. The error disappeared.
you can wrap your textfield in IgnorePointer widget. It disables all the gestures on its children. This will make gesture detector work.
title: new GestureDetector(
child: new IgnorePointer (
child: new TextField(
controller: searchController,
decoration: new InputDecoration(
hintText: 'Buscar parcela', border: InputBorder.none),
))),
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => new EstatesPage(
parcela: widget.parcela,
dropdownItem: dropdownSelection)));
},
TextField has onTap property like GestureDetector which makes it very easy. If you only want the onTap functionality set readOnly to true.
TextField(
readOnly: true,
onTap: () {
//Your code here
},
[...]
);
Similarly for TextFormField:
TextFormField(
readOnly: true,
onTap: () {
//Your code here
},
[...]
);
GestureDetector didn't work for me. I used InkWell.
child: InkWell(
onTap: () {
_selectDate(context);
},
child: const IgnorePointer(
child: TextField(
decoration: InputDecoration(
labelText: 'Date',
hintText: 'Enter Date',
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.calendar_today_outlined),
),
),
),
),
and it worked fine
It works for me when I use InkWell instead of GestureDetector
InkWell(
child: IgnorePointer(
child: TextField(
)
),
onTap: (){
}
)
use readonly: false for on tap action in text field
TextField(
readOnly: true,
onTap: () {
// open dialogue
}
);

Flutter - Showing suggestion list on top of other widgets

I am developing a screen where I have to show suggestions list below the textfield.
I want to achieve this
I have developed this so far
Following code shows textfield with suggestions in a list.
#override
Widget build(BuildContext context) {
final header = new Container(
height: 39.0,
padding: const EdgeInsets.only(left: 16.0, right: 2.0),
decoration: _textFieldBorderDecoration,
child: new Row(
children: <Widget>[
new Expanded(
child: new TextField(
maxLines: 1,
controller: _controller,
style: _textFieldTextStyle,
decoration:
const InputDecoration.collapsed(hintText: 'Enter location'),
onChanged: (v) {
_onTextChanged.add(v);
if (widget.onStartTyping != null) {
widget.onStartTyping();
}
},
),
),
new Container(
height: 32.0,
width: 32.0,
child: new InkWell(
child: new Icon(
Icons.clear,
size: 20.0,
color: const Color(0xFF7C7C7C),
),
borderRadius: new BorderRadius.circular(35.0),
onTap: (){
setState(() {
_controller.clear();
_places = [];
if (widget.onClearPressed != null) {
widget.onClearPressed();
}
});
},
),
),
],
),
);
if (_places.length > 0) {
final body = new Material(
elevation: 8.0,
child: new SingleChildScrollView(
child: new ListBody(
children: _places.map((p) {
return new InkWell(
child: new Container(
height: 38.0,
padding: const EdgeInsets.only(left: 16.0, right: 16.0),
alignment: Alignment.centerLeft,
decoration: _suggestionBorderDecoration,
child: new Text(
p.formattedAddress,
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: _suggestionTextStyle,
),
),
onTap: () {
_getPlaceDetail(p);
},
);
}).toList(growable: false),
),
),
);
return new Container(
child: new Column(
children: <Widget>[header, body],
),
);
} else {
return new Container(
child: new Column(
children: <Widget>[header],
),
);
}
}
Header(Textfield) and body(Suggestions List - SingleChildScrollView with ListBody) is wrapped inside the Column widget, and column expands based on the total height of the children.
Now the problem is as Column expands, layout system pushes other widgets on screen to the bottom. But I want other widgets to stay on their positions but suggestion list starts to appear on top of other widgets.
How can I show suggestions list on top of other widgets? And the suggestions list is dynamic, as user types I call the Google Places API and update the suggestions list.
I have seen there is showMenu<T>() method with RelativeRect positions but it doesn't fulfills my purpose, my suggestion list is dynamic(changing based on user input) and the styling for each item I have is different from what PopupMenuItem provides.
There is one possibility I can think of using Stack widget as root widget of this screen and arrange everything by absolute position and I put suggestion list as a last child of the stack children list. But it is not the right solution I believe.
What other possibilities I need to look into? What other Widgets can be used here in this use-case?
And again use-case is simple, overlaying suggestion list on other widgets on the screen and when user tap any of the item from the list then hiding this overlaid suggestion list.
The reason why your autocomplete list pushes down the widgets below it is because the List is being expanded on the Container. You can use Flutter's Autocomplete widget and it should inflate the autocomplete list over other widgets.
var fruits = ['Apple', 'Banana', 'Mango', 'Orange'];
_autoCompleteTextField() {
return Autocomplete(
optionsBuilder: (TextEditingValue textEditingValue) {
if (textEditingValue.text == '') {
return const Iterable<String>.empty();
}
return fruits.where((String option) {
return option
.toLowerCase()
.contains(textEditingValue.text.toLowerCase());
});
},
onSelected: (String selection) {
debugPrint('You just selected $selection');
},
);
}

When I select a Textfield the keyboard moves over it

When i select a Textfield, the keyboard is going to be shown but the keyboard hide my selected TextField. Does someone have a solution?
Scaffold(
resizeToAvoidBottomInset: true,
body: SingleChildScrollView(
child: Container(
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(
labelText: 'Enter Text',
),
),TextFormField(
decoration: InputDecoration(
labelText: 'Enter Text',
),
),TextFormField(
decoration: InputDecoration(
labelText: 'Enter Text',
),
),TextFormField(
decoration: InputDecoration(
labelText: 'Enter Text',
),
),TextFormField(
decoration: InputDecoration(
labelText: 'Enter Text',
),
),TextFormField(
decoration: InputDecoration(
labelText: 'Enter Text',
),
),TextFormField(
decoration: InputDecoration(
labelText: 'Enter Text',
),
),
TextFormField(
decoration: InputDecoration(
labelText: 'Enter Text',
),
)
],
),
),
)
);
// resizeToAvoidBottomPadding: false isDeprecated
use resizeToAvoidBottomInset: true.
Compose an animation and move your TextField container up when a TextField gets focus.
For learning about composing animations refer to:
Composing Animations and Chaining Animations in Dart's Flutter Framework
Use Flutter's FocusNode to detect the focus on a TextField
Edit:
Here I've written an example that does exactly what you want:
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Animation Demo',
theme: new ThemeData(
primaryColor: new Color(0xFFFF0000),
),
home: new FormDemo(),
);
}
}
class FormDemo extends StatefulWidget {
#override
_FormDemoState createState() => _FormDemoState();
}
class _FormDemoState extends State<FormDemo> with SingleTickerProviderStateMixin {
AnimationController _controller;
Animation _animation;
FocusNode _focusNode = FocusNode();
#override
void initState() {
super.initState();
_controller = AnimationController(vsync: this, duration: Duration(milliseconds: 300));
_animation = Tween(begin: 300.0, end: 50.0).animate(_controller)
..addListener(() {
setState(() {});
});
_focusNode.addListener(() {
if (_focusNode.hasFocus) {
_controller.forward();
} else {
_controller.reverse();
}
});
}
#override
void dispose() {
_controller.dispose();
_focusNode.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: false, // this avoids the overflow error
appBar: AppBar(
title: Text('TextField Animation Demo'),
),
body: new InkWell( // to dismiss the keyboard when the user tabs out of the TextField
splashColor: Colors.transparent,
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
child: Container(
padding: const EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
SizedBox(height: _animation.value),
TextFormField(
decoration: InputDecoration(
labelText: 'I move!',
),
focusNode: _focusNode,
)
],
),
),
),
);
}
}
Just cut and paste your body code in this -
SingleChildScrollView(
child: Stack(
children: <Widget>[
// your body code
],
),
),
A pretty short way to realize this is by simply using a MediaQuery for getting the bottom view insets. This would look as follows:
...
return Column(
children: <Widget>[
TextField(
decoration: InputDecoration.collapsed(hintText: "Start typing ..."),
controller: _chatController,
),
SizedBox(
height: MediaQuery.of(context).viewInsets.bottom,
),
],
);
...
Hope it helps!
In my case I had to combine answer given by #Javid Noutash which uses AnimationController along with scrollPadding property of TextFormField.
code:
Add this line in build method
double bottomInsets = MediaQuery.of(context).viewInsets.bottom;
Add scrollPadding property
return ListView(
children:[
...widgets,
Container(
margin:EdgeInsets.only(
top:1.0,
left:1.0,
right:1.0,
bottom:_focusNode.hasFocus && bottomInsets != 0?
_animation.value : 1.0),
child:TextFormField(
decoration: InputDecoration(
labelText: 'I move!',
),
focusNode: _focusNode,
scrollPadding: EdgeInsets.only(bottom:bottomInsets + 40.0),
),
),
]
);
Note: Combine this code with #Javid Noutash's code
I had the same problem where the parent widget is Material and the other widgets are inside a ListView. The problem was fixed when I changed the parent widget to Scaffold without any extra code and the TextField, TextFormField in my case, is being showed above the Keyboard automatically. So, if you encountered this problem just make sure to have Scaffold as the main widget.
The most simple way is to just wrap it with
SingleChildScrollView( ... )
When the textfield is on the page bottom and the keyboard appears, the textfield is automatically scrolled up. Then the text may be entered right above the keyboard.
My way here
Scaffold(
resizeToAvoidBottomInset: false,
resizeToAvoidBottomPadding: false,
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('images/Bg img.png'), fit: BoxFit.fill)),
child: Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom),
child: CustomScrollView(
slivers: [
SliverFillRemaining(
hasScrollBody: false,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
.............
This template has some advantages:
Move content up when the keyboard appears
Column using spaceBetween inside a scroll view
Background is sticked phone scren and never change event the keyboard ups
Wrap your widget into Padding and set padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
<activity
android:name="..ActivityName"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize"/>
only for android
if you use FlutterFragment add configChanges and windowSoftInputMode for the Activity.
another way
add your TextField to a ListView
ListView(
children: <Widget>[
TextField(),
TextField(),
]
)
The above does not work if you have a CustomScrollview in a NestedScrollView.
First, you need to give the TextField a focusNode.
TextField(focusNode:_focusNode(),
...);
Use NestedScrollViewState to get access to the innerScrollController of the NestedScrollView. You can view the example here on how to get the innerScrollController. Declare a globalKey and assign it to NestedScrollView.
body: NestedScrollView(
key: globalKey,
...)
Setup the focusNode Listener to listen for when the textfield has been activated and animate the innerScrollController accordingly.
void initState() {
super.initState();
_focusNode.addListener(() {
if (_focusNode.hasFocus) {
double innerOffSet = globalKey.currentState.innerController.offset;
if(innerOffSet < 100)
globalKey.currentState.innerController.jumpTo(innerOffSet+100);
}
});
}
var _contentController;
void _settingModalBottomSheet(BuildContext context, String initialText) {
_contentController = new TextEditingController(text: initialText);
showModalBottomSheet(
context: context,
isDismissible: true,
builder: (BuildContext bc) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
height: 40,
margin: EdgeInsets.only(left: 4, right: 4, bottom: 8),
decoration: BoxDecoration(
color: AppColor.bgTextFieldComment,
borderRadius: BorderRadius.circular(16),
),
child: Row(
children: <Widget>[
Expanded(
child: Padding(
padding: EdgeInsets.only(left: 24),
child: TextField(
focusNode: _contentFocusNode,
autofocus: true,
controller: _contentController,
decoration: InputDecoration(
hintText: 'Enter Content',
border: InputBorder.none,
fillColor: AppColor.bgTextFieldComment,
),
keyboardType: TextInputType.multiline,
maxLines: null,
style: TextStyle(
color: Colors.black87,
fontSize: 16,
fontStyle: FontStyle.normal,
),
)),
),
InkWell(
child: Padding(
padding: EdgeInsets.only(left: 4, right: 4),
child: Icon(
Icons.send,
color: Colors.blue,
),
),
onTap: () {
// do ON TAP
},
),
],
),
),
SizedBox(
height: MediaQuery.of(bc).viewInsets.bottom,
),
],
);
},).then((value) {
print('Exit Modal');
});
print('request focus');
_contentFocusNode.requestFocus();
}
Instead of TextField, use TextFormField and wrap the widget with a list of TextFormField to Form:
Form(
child: Column(
children: <Widget> [
TextFormField(),
TextFormField(),
...
TextFormField(),
]
)
)
you can easily try to use Flexible widget just wrap your widget with it
Flexible(
child: Image(
image :
AssetImage('assets/logo.png'),
),
),
I had a very complex widget with Stack, Column and Single ChildChildScrollView, and I fixed it by adding a padding to the SCSV like this:
child: Stack(
children: [
Padding(
padding: const EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
child: SingleChildScrollView(
child: Column(
children: [... a lot of children here, one of them is a TextField],
),
),
),
// a widget at the bottom of the stack that shows despite the size of the scrollable column
],
),
It's very easy in my case check out code
Column(
children: [
Expanded(
child:// Top View,
),
postSend // edittext. and button
],
)

IconButton throws an exception

I'm trying to make a simple AppBar widget with some icons in Flutter, but I keep getting this assertion:
The following assertion was thrown building IconButton(Icon(IconData(U+0E5D2)); disabled; tooltip:
I pretty much just mimiced the documentation, but here is my code:
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
title: "Stateless Widget Example",
home: new AppBar(title: new Text("App Bar"))
));
}
class AppBar extends StatelessWidget {
AppBar({this.title});
final Widget title;
#override
Widget build(BuildContext context) {
return new Container(
height: 56.0,
padding: const EdgeInsets.symmetric(horizontal: 8.0),
decoration: new BoxDecoration(
color: Colors.cyan,
border: new Border(
bottom: new BorderSide(
width: 1.0,
color: Colors.black
)
)
),
child: new Row (
children: <Widget> [
new IconButton(
icon: new Icon(Icons.menu),
tooltip: 'Navigation menu',
onPressed: null, // null disables the button
),
new Expanded(child: title)
]
)
);
}
}
I feel like I'm missing an import or something. But I'm not completely sure. Perhaps my computer was just acting up, because Flutter run has been buggy for me. I'm new to Dart and Flutter, so perhaps I'm just not seeing an obvious error.
IconButton is a Material Widget, so you need to use it inside a Material parent, for example something like this:
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text(widget.title), actions: <Widget>[
new IconButton(
icon: new Icon(Icons.favorite),
tooltip: 'Favorite',
onPressed: () {},
),
new IconButton(
icon: new Icon(Icons.more_vert),
tooltip: 'Navigation menu',
onPressed: () {},
),
]),
body: new Center(
child: new Text('This is the body of the page.'),
),
);
}
Check to ensure that your pubspec.yaml contains the following:
flutter:
uses-material-design: true
That will ensure that the Material Icons font is included with your application, so that you can use the icons in the Icons class.
addButton() {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(vertical: 10.0),
child: SizedBox(
height: 45,
width: 200,
child: ElevatedButton.icon(
onPressed: () async {},
style: ButtonStyle(
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
)),
elevation: MaterialStateProperty.all(1),
backgroundColor: MaterialStateProperty.all(Colors.blue),
),
icon: Icon(Icons.add, size: 18),
label: Text("Add question"),
),
),
),
],
);
}
you lost meterial widget
IconButton needs Material
return new Material(
child: new Container(
height: 56.0,
padding: const EdgeInsets.symmetric(horizontal: 8.0),
decoration: new BoxDecoration(
color: Colors.cyan,
border: new Border(
bottom: new BorderSide(
width: 1.0,
color: Colors.black
)
)
),
child: new Row (
children: <Widget> [
new IconButton(
icon: new Icon(Icons.menu),
tooltip: 'Navigation menu',
onPressed: null, // null disables the button
),
new Expanded(child: title)
]
)
);

Resources