GridView onTap is only called during creation - dart

I made a GridView with children that each has a GestureDetector and a onTap method set. But the onTap event gets called only when the view is created and not when the item has been tapped. What am I doing wrong here?
class MyGridView extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Column(
children: <Widget>[
new Expanded(
child: new GridView.count(
crossAxisCount: 2,
children: [
new GridItem(0),
new GridItem(1)
]
)
)
]
);
}
}
class GridItem extends StatelessWidget {
final int code;
GridItem(this.code);
#override
Widget build(BuildContext context) {
return new GestureDetector(
onTap: print(code),
child: new Container(
height: 48.0,
child: new Text('$code')
)
);
}
}

You want:
onTap: () { print(code); },
What you're doing is calling print, then saving the return value from print (which will be a null) as the onTap handler, which actually disables the onTap handler. If you see anything in the logs it'll be from the time you actually did the build, not when you tapped.

Related

Flutter - Not being able to change tab using a FAB instead of TabBar Icons

I am trying to make a small notes app and I had the idea that instead of using a different page for the creation section of the app to use a different tab that is only accessible by an "add" fab in the main screen. Also I want it such that after you press the button it turns it into a "back" button which takes you back to the original page with the notes list.
class HomePage extends StatefulWidget {
const HomePage({Key key}) : super(key: key);
static final _myTabbedPageKey = new GlobalKey<HomePageState>();
#override
HomePageState createState() => HomePageState();
}
class HomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
TabController tController;
#override
void initState(){
super.initState();
tController = new TabController(vsync: this, length: 2,);
}
#override
void dispose(){
tController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("NoteMe"),
),
body: Container(
child: TabBarView(
physics: NeverScrollableScrollPhysics(),
controller: tController,
children: <Widget>[
new ListPage(),
new CreationPage(),
],
)
),
floatingActionButton: actionButton(tController),
floatingActionButtonLocation: FloatingActionButtonLocation.endDocked,
bottomNavigationBar: BottomAppBar(
shape: CircularNotchedRectangle(),
child: Row(
children: <Widget>[
new Container(
child: IconButton(
icon: Icon(Icons.search),
onPressed: () {},
)),
],
),
),
);
}
}
//Implementing the ADD/RETURN Button as func
FloatingActionButton actionButton(TabController tC){
bool isListPage = true;
goToCreation(){
if(isListPage == true){
tC.animateTo(tC.index+1);
isListPage = false;
}
else{
tC.animateTo(tC.index - 1);
isListPage = true;
}
}
FloatingActionButton theButton = FloatingActionButton(
backgroundColor: kColorPink,
elevation: 2.0,
child: isListPage == true ? Icon(Icons.add) : Icon(Icons.arrow_back),
onPressed: goToCreation(),
);
return theButton;
}
As you can see the fab that is displayed is returned by the function above that also takes the tabcontroller as a parameter. I get no error message while running this. It simply does not work. I have tried not passing the tabController but instead accessing it through something like
HomePage._myTabbedPageKey.tController.animateTo(...)
that I have found in another post but that's when I get an error message stating something like calling tController on null.
Sorry if I didn't format this well enough. This is my first post here
It may be that the reference to tc or event goToCreation is null.
Can you put a breakpoint in the method and check if the method is called and if the tc object is not null.

Flutter Switch widget does not work if created inside initState()

I am trying to create a Switch widget add it to a List of widgets inside the initState and then add this list to the children property of a Column in the build method. The app runs successfully and the Switch widget does show but clicking it does not change it as if it is not working. I have tried making the same widget inside the build method and the Switch works as expected.
I have added some comments in the _onClicked which I have assigned to the onChanged property of the Switch widget that show the flow of the value property.
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
home: App(),
));
}
class App extends StatefulWidget {
#override
AppState createState() => new AppState();
}
class AppState extends State<App> {
List<Widget> widgetList = new List<Widget>();
bool _value = false;
void _onClicked(bool value) {
print(_value); // prints false the first time and true for the rest
setState(() {
_value = value;
});
print(_value); // Always prints true
}
#override
void initState() {
Switch myWidget = new Switch(value: _value, onChanged: _onClicked);
widgetList.add(myWidget);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('My AppBar'),
),
body: new Container(
padding: new EdgeInsets.all(32.0),
child: new Center(
child: new Column(children: widgetList),
),
),
);
}
}
initState is to initialize the state, not widgets. build is to create widgets.
There reason it fails is because the widgets needs to be rebuilt when the value changes (when you call setState), but it isn't because when build() is called, the previously (in initState) created widget is reused.
#override
Widget build(BuildContext context) {
List<Widget> widgetList = [];
Switch myWidget = new Switch(value: _value, onChanged: _onClicked);
widgetList.add(myWidget);
return new Scaffold(
appBar: new AppBar(
title: new Text('My AppBar'),
),
body: new Container(
padding: new EdgeInsets.all(32.0),
child: new Center(
child: new Column(children: widgetList),
),
),
);
}

Flutter Switching to Tab Reloads Widgets and runs FutureBuilder

The issue:
I have 2 tabs using Default Tabs Controller, like so:
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
drawer: Menu(),
appBar: AppBar(
title: Container(
child: Text('Dashboard'),
),
bottom: TabBar(
tabs: <Widget>[
Container(
padding: EdgeInsets.all(8.0),
child: Text('Deals'),
),
Container(
padding: EdgeInsets.all(8.0),
child: Text('Viewer'),
),
],
),
),
body: TabBarView(
children: <Widget>[
DealList(),
ViewersPage(),
],
),
),
);
}
}
The DealList() is a StatefulWidget which is built like this:
Widget build(BuildContext context) {
return FutureBuilder(
future: this.loadDeals(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
print('Has error: ${snapshot.hasError}');
print('Has data: ${snapshot.hasData}');
print('Snapshot data: ${snapshot.data}');
return snapshot.connectionState == ConnectionState.done
? RefreshIndicator(
onRefresh: showSomething,
child: ListView.builder(
physics: const AlwaysScrollableScrollPhysics(),
itemCount: snapshot.data['deals'].length,
itemBuilder: (context, index) {
final Map deal = snapshot.data['deals'][index];
print('A Deal: ${deal}');
return _getDealItem(deal, context);
},
),
)
: Center(
child: CircularProgressIndicator(),
);
},
);
}
}
With the above, here's what happens whenever I switch back to the DealList() tab: It reloads.
Is there a way to prevent re-run of the FutureBuilder when done once? (the plan is for user to use the RefreshIndicator to reload. So changing tabs should not trigger anything, unless explicitly done so by user.)
There are two issues here, the first:
When the TabController switches tabs, it unloads the old widget tree to save memory. If you want to change this behavior, you need to mixin AutomaticKeepAliveClientMixin to your tab widget's state.
class _DealListState extends State<DealList> with AutomaticKeepAliveClientMixin<DealList> {
#override
bool get wantKeepAlive => true;
#override
Widget build(BuildContext context) {
super.build(context); // need to call super method.
return /* ... */
}
}
The second issue is in your use of the FutureBuilder -
If you provide a new Future to a FutureBuilder, it can't tell that the results would be the same as the last time, so it has to rebuild. (Remember that Flutter may call your build method up to once a frame).
return FutureBuilder(
future: this.loadDeals(), // Creates a new future on every build invocation.
/* ... */
);
Instead, you want to assign the future to a member on your State class in initState, and then pass this value to the FutureBuilder. The ensures that the future is the same on subsequent rebuilds. If you want to force the State to reload the deals, you can always create a method which reassigns the _loadingDeals member and calls setState.
Future<...> _loadingDeals;
#override
void initState() {
_loadingDeals = loadDeals(); // only create the future once.
super.initState();
}
#override
Widget build(BuildContext context) {
super.build(context); // because we use the keep alive mixin.
return new FutureBuilder(future: _loadingDeals, /* ... */);
}

Can't get button press to work in flutter

Ok I'm pretty new to flutter/ dart so go easy on me. I'm just trying to make a very simple app where when you press a button some text updates telling you how many times you have pressed the button. I have no idea why this code doesn't work. The button appears but nothing happens when you press it.
import 'package:flutter/material.dart';
class Homepage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Column(
children: <Widget>[],
);
}
}
class Buttonz extends StatefulWidget {
#override
_ButtonBeingPressed createState() => new _ButtonBeingPressed();
}
class _ButtonBeingPressed extends State<Buttonz> {
int _timesPressed = 0;
_buttonWasPressed() {
setState(() {
_timesPressed++;
});
}
#override
Widget build(BuildContext context) {
return new Column(children: <Widget>[
new Center(
child: new Row(
children: <Widget>[
new Text(
'The button was pressed ' + _timesPressed.toString() + "
times"),
new RaisedButton(
onPressed: _buttonWasPressed(),
child: new Row(
children: <Widget>[new Text("Press meh")],
),
),
],
))
]);
}
}
Your problem is that you didn't pass a callback to RaisedButton, you invoked your callback.
new RaisedButton(
onPressed: _buttonWasPressed(), // invokes function
child: new Row(children: <Widget>[new Text("Press meh")]),
);
To pass a callback to another widget you have two choices:
Pass a tear-off
new RaisedButton(
onPressed: _buttonWasPressed, // no `()`,
child: ...
)
Pass a closure
new RaisedButton(
onPressed: () {
// do something.
},
..
)
in some cases, this can occur with a widget in the stack.
It is possible that the Widget is overwritten with another Widget, so it cannot be clicked.
Added a Material App and rewired the RaisedButton a little. I think it was how you had onPressed wired up.
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(home: new Buttonz());
}
}
class Buttonz extends StatefulWidget {
#override
_ButtonBeingPressed createState() => new _ButtonBeingPressed();
}
class _ButtonBeingPressed extends State<Buttonz> {
int _timesPressed = 0;
_buttonWasPressed() {
setState(() {
_timesPressed++;
});
}
#override
Widget build(BuildContext context) {
return new Column(
children: <Widget>[
new Text(
'The button was pressed $_timesPressed times'),
new RaisedButton(
child: const Text('Press meh'),
onPressed: () {
_buttonWasPressed();
},
),
],
);
}
}
Your button should be like this.:
new RaisedButton(
child: const Text('Press meh'),
onPressed: _buttonWasPressed,
),
If this doesn't work, then try to clean your flutter project with flutter clean and then reinstalling the app on debug device.

Overflowing parent widgets

I'm trying to create a widget that has a button and whenever that button is pressed, a list opens up underneath it filling in all of the space under the button. I implemented it with a simple Column, something like this:
class _MyCoolWidgetState extends State<MyCoolWidget> {
...
#override
Widget build(BuildContext context) {
return new Column(
children: <Widget>[
new MyButton(...),
isPressed ? new Expanded(
child: new SizedBox(
width: MediaQuery.of(context).size.width,
child: new MyList()
)
) : new Container()
]
)
}
}
This works totally fine in a lot of cases, but not all.
The problem I'm having with creating this widget is that if a MyCoolWidget is placed inside a Row for example with other widgets, lets say other MyCoolWidgets, the list is constrained by the width that the Row implies on it.
I tried fixing this with an OverflowBox, but with no luck unfortunately.
This widget is different from tabs in the sense that they can be placed anywhere in the widget tree and when the button is pressed, the list will fill up all the space under the button even if this means neglecting constraints.
The following image is a representation of what I'm trying to achieve in which "BUTTON1" and "BUTTON2" or both MyCoolWidgets in a Row:
Edit: Snippet of the actual code
class _MyCoolWidgetState extends State<MyCoolWidget> {
bool isTapped = false;
#override
Widget build(BuildContext context) {
return new Column(
children: <Widget>[
new SizedBox(
height: 20.0,
width: 55.0,
child: new Material(
color: Colors.red,
child: new InkWell(
onTap: () => setState(() => isTapped = !isTapped),
child: new Text("Surprise"),
),
),
),
bottomList()
],
);
}
Widget comboList() {
if (isTapped) {
return new Expanded(
child: new OverflowBox(
child: new Container(
color: Colors.orange,
width: MediaQuery.of(context).size.width,
child: new ListView( // Random list
children: <Widget>[
new Text("ok"),
new Text("ok"),
new Text("ok"),
new Text("ok"),
new Text("ok"),
new Text("ok"),
new Text("ok"),
new Text("ok"),
new Text("ok"),
new Text("ok"),
new Text("ok"),
new Text("ok"),
new Text("ok"),
],
)
)
),
);
} else {
return new Container();
}
}
}
I'm using it as follows:
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Row(
children: <Widget>[
new Expanded(child: new MyCoolWidget()),
new Expanded(child: new MyCoolWidget()),
]
)
}
}
Here is a screenshot of what the code is actually doing:
From the comments, it was clarified that what the OP wants is this:
Making a popup that covers everything and goes from wherever the button is on the screen to the bottom of the screen, while also filling it horizontally, regardless of where the button is on the screen. It would also toggle open/closed when the button is pressed.
There are a few options for how this could be done; the most basic would be to use a Dialog & showDialog, except that it has some issues around SafeArea that make that difficult. Also, the OP is asking for the button to toggle rather than pressing anywhere not the dialog (which is what dialog does - either that or blocks touches behind the dialog).
This is a working example of how to do something like this. Full disclaimer - I'm not stating that this is a good thing to do, or even a good way to do it... but it is a way to do it.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
// We're extending PopupRoute as it (and ModalRoute) do a lot of things
// that we don't want to have to re-create. Unfortunately ModalRoute also
// adds a modal barrier which we don't want, so we have to do a slightly messy
// workaround for that. And this has a few properties we don't really care about.
class NoBarrierPopupRoute<T> extends PopupRoute<T> {
NoBarrierPopupRoute({#required this.builder});
final WidgetBuilder builder;
#override
Color barrierColor;
#override
bool barrierDismissible = true;
#override
String barrierLabel;
#override
Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
return new Builder(builder: builder);
}
#override
Duration get transitionDuration => const Duration(milliseconds: 100);
#override
Iterable<OverlayEntry> createOverlayEntries() sync* {
// modalRoute creates two overlays - the modal barrier, then the
// actual one we want that displays our page. We simply don't
// return the modal barrier.
// Note that if you want a tap anywhere that isn't the dialog (list)
// to close it, then you could delete this override.
yield super.createOverlayEntries().last;
}
#override
Widget buildTransitions(
BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
// if you don't want a transition, remove this and set transitionDuration to 0.
return new FadeTransition(opacity: new CurvedAnimation(parent: animation, curve: Curves.easeOut), child: child);
}
}
class PopupButton extends StatefulWidget {
final String text;
final WidgetBuilder popupBuilder;
PopupButton({#required this.text, #required this.popupBuilder});
#override
State<StatefulWidget> createState() => PopupButtonState();
}
class PopupButtonState extends State<PopupButton> {
bool _active = false;
#override
Widget build(BuildContext context) {
return new FlatButton(
onPressed: () {
if (_active) {
Navigator.of(context).pop();
} else {
RenderBox renderbox = context.findRenderObject();
Offset globalCoord = renderbox.localToGlobal(new Offset(0.0, context.size.height));
setState(() => _active = true);
Navigator
.of(context, rootNavigator: true)
.push(
new NoBarrierPopupRoute(
builder: (context) => new Padding(
padding: new EdgeInsets.only(top: globalCoord.dy),
child: new Builder(builder: widget.popupBuilder),
),
),
)
.then((val) => setState(() => _active = false));
}
},
child: new Text(widget.text),
);
}
}
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new SafeArea(
child: new Container(
color: Colors.white,
child: new Column(children: [
new PopupButton(
text: "one",
popupBuilder: (context) => new Container(
color: Colors.blue,
),
),
new PopupButton(
text: "two",
popupBuilder: (context) => new Container(color: Colors.red),
)
]),
),
),
);
}
}
For even more outlandish suggestions, you can take the finding the location part of this and look at this answer which describes how to create a child that isn't constrained by it's parent's position.
However you end up doing this, it's probably best that the list not to be a direct child of the button as a lot of things in flutter depend on a child's sizing and making it be able to expand to the full screen size could quite easily cause problems.

Resources