Created
January 14, 2019 15:48
-
-
Save brianegan/b4f5e051874e000d8efd157837be8b72 to your computer and use it in GitHub Desktop.
Changing tabs with a callback function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
home: MyTabbedPage(), | |
); | |
} | |
} | |
class MyTabbedPage extends StatefulWidget { | |
const MyTabbedPage({Key key}) : super(key: key); | |
@override | |
_MyTabbedPageState createState() => _MyTabbedPageState(); | |
} | |
class _MyTabbedPageState extends State<MyTabbedPage> | |
with SingleTickerProviderStateMixin { | |
final List<Tab> myTabs = <Tab>[ | |
Tab(text: 'LEFT'), | |
Tab(text: 'RIGHT'), | |
]; | |
TabController _tabController; | |
@override | |
void initState() { | |
super.initState(); | |
_tabController = TabController(vsync: this, length: myTabs.length); | |
} | |
@override | |
void dispose() { | |
_tabController.dispose(); | |
super.dispose(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text("Tab demo"), | |
bottom: TabBar( | |
controller: _tabController, | |
tabs: myTabs, | |
), | |
), | |
body: TabBarView( | |
controller: _tabController, | |
children: List.generate( | |
myTabs.length, | |
(i) { | |
return MyTabPage( | |
onButtonTap: () => | |
_tabController.animateTo(i + 1 >= myTabs.length ? 0 : i + 1), | |
onButtonTapWithIndex: _tabController.animateTo, | |
); | |
}, | |
), | |
), | |
); | |
} | |
} | |
class MyTabPage extends StatelessWidget { | |
final Function() onButtonTap; | |
final Function(int) onButtonTapWithIndex; | |
const MyTabPage({ | |
Key key, | |
@required this.onButtonTap, | |
@required this.onButtonTapWithIndex, | |
}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
RaisedButton( | |
child: Text("Go to next tab"), | |
onPressed: onButtonTap, | |
), | |
RaisedButton( | |
child: Text("Go to tab at index 1"), | |
onPressed: () => onButtonTapWithIndex(1), | |
) | |
], | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment