Skip to content

Instantly share code, notes, and snippets.

@rmarau
Created May 28, 2019 18:57
Show Gist options
  • Save rmarau/b3412f636c4cddec375ff1055a0566f8 to your computer and use it in GitHub Desktop.
Save rmarau/b3412f636c4cddec375ff1055a0566f8 to your computer and use it in GitHub Desktop.
Dynamic Tabs + extendBody
import 'package:flutter/material.dart';
import 'dart:math';
void main() => runApp(
MaterialApp(
home: MyHomePage(),
)
);
enum Mode{default_, custom}
const cntrlMode = Mode.default_;
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
TabController _tabcontroller;
List<int> _tabs = [1];
@override
void initState() {
_tabcontroller = (cntrlMode==Mode.custom)
? TabController(vsync: this, length: _tabs.length, )
: null;
super.initState();
}
@override
void dispose() {
_tabcontroller?.dispose();
super.dispose();
}
void _incrementTabs() {
setState(() {
_tabs.add(_tabs.last+1);
//Cannot use this
//if (cntrlMode==Mode.custom) _tabcontroller = TabController(vsync: this, length: _tabs.length), );
_tabcontroller = _tabcontroller?.copyWith(length: _tabs.length); //I've made copyWith public in flutter
});
}
void _decrementTabs(element) {
if (_tabs.length==1)
return;
setState(() {
_tabs.remove(element);
//Cannot use this
// if (cntrlMode==Mode.custom) {
// _tabcontroller = TabController(vsync: this,
// length: _tabs.length,
// )
// ..index = min(_tabs.length-1, _tabcontroller.index);
// }
_tabcontroller = _tabcontroller?.copyWith( //I've made copyWith public in flutter
length: _tabs.length,
index: min(_tabs.length-1, _tabcontroller.index),
previousIndex: min(_tabs.length-1, _tabcontroller.previousIndex),
);
});
}
_getScafold() => Scaffold(
appBar: AppBar(
title: Text("Dynamic Tabs"),
bottom: TabBar(
isScrollable: true,
tabs: _tabs.map<Widget>((tab)=>Tab(icon: Icon(Icons.star), text: "$tab")).toList(),
controller: _tabcontroller, //null if Mode.default_
),
),
body: TabBarView(
controller: _tabcontroller, //null if Mode.default_
children: _tabs.map<Widget>((tab)=>
Center(child: RaisedButton(
child: Text("Remove Tab $tab"),
onPressed: () => _decrementTabs(tab),
),),
).toList(),
),
extendBody: true, //Show body behind notch
floatingActionButton: FloatingActionButton(
onPressed: _incrementTabs,
child: Icon(Icons.add),
),
);
@override
Widget build(BuildContext context) {
return cntrlMode==Mode.default_
? DefaultTabController(
length: _tabs.length,
child: _getScafold(),
)
: _getScafold();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment