Flutter中禁用滑动到指定加号Tab的实现方法
Flutter 禁用滑动到加号新增Tab的问题求助
我正在使用Flutter开发应用,需要实现禁用滑动到带有加号图标的新增Tab的功能。尝试过ChatGPT但没得到有效解决办法,毫无头绪,现附上代码,恳请各位提供帮助!
import 'package:flutter/material.dart'; class workout_page extends StatefulWidget { @override _WorkoutPageState createState() => _WorkoutPageState(); } class _WorkoutPageState extends State<workout_page> with TickerProviderStateMixin { late TabController _tabController; List<Map<String, dynamic>> workoutMap = [ { 'name': 'My First Workout', 'exercises': [ { 'name': 'Bicep Curl', 'musclesworked': ['bicep', 'tricep'] }, { 'name': 'Preacher Curl', 'musclesworked': ['bicep', 'tricep'] } ] }, ]; @override void initState() { super.initState(); _tabController = TabController(length: workoutMap.length + 1, vsync: this); } TextEditingController _newTabController = TextEditingController(); void _addTab() { setState(() { String newTabName = _newTabController.text; Map<String, dynamic> newTab = { 'name': newTabName, 'exercises': [], }; workoutMap.add(newTab); _newTabController.clear(); _tabController = TabController( length: workoutMap.length + (workoutMap.length < 4 ? 1 : 0), vsync: this, ); }); } @override Widget build(BuildContext context) { Size size = MediaQuery.of(context).size; return DefaultTabController( length: workoutMap.length + (workoutMap.length < 4 ? 1 : 0), child: Scaffold( backgroundColor: Color.fromRGBO(79, 79, 79, 1), appBar: PreferredSize( preferredSize: Size.fromHeight(60), child: AppBar( backgroundColor: Color.fromARGB(255, 19, 19, 19), centerTitle: false, flexibleSpace: Column( children: [ SizedBox(height: size.height * .061), TabBar( controller: _tabController, tabs: [ ...workoutMap .map((tab) => Tab(text: tab['name'] as String)), if (workoutMap.length < 4) Container( width: 40, height: 40, alignment: Alignment.center, child: IconButton( icon: Icon(Icons.add), onPressed: () { showDialog( context: context, builder: (context) => AlertDialog( title: Text('Add Tab'), content: TextField( controller: _newTabController, decoration: InputDecoration( hintText: 'Enter tab name', ), ), actions: [ TextButton( child: Text('Cancel'), onPressed: () { Navigator.pop(context); }, ), TextButton( child: Text('Add'), onPressed: () { _addTab(); Navigator.pop(context); }, ), ], ), ); }, ), ), ], ), ], ), ), ), body: TabBarView( controller: _tabController, children: [ ...workoutMap.map((tab) => Column( children: [ Text(tab['name'] as String), ], )), if (workoutMap.length < 4) Container(), ], ), ), ); } }
PS:为发布此内容特添加本段,再次感谢各位!
内容的提问来源于stack exchange,提问作者Cidiko Andorem
相关产品推荐
相关产品推荐

