我正在處理一個顫振專案,其中我需要使用相同的浮動操作按鈕觸發兩個不同的代碼:
這是我的選項卡視圖:
appBar: AppBar(
bottom: TabBar(indicator: BoxDecoration(
color: Colors.black12, borderRadius: BorderRadius.circular(0),
),
tabs: [
Tab(text: 'Drivers'),
Tab(text:'Cars')
],
labelColor: Colors.pink,
),
和我的標簽欄視圖:
body: TabBarView(
children:[
SingleChildScrollView(...),
Center(child: Text('add car screen'))
]
),
和一個浮動按鈕:
floatingActionButton: FloatingActionButton(
onPressed: () {
// Add your onPressed code here!
},
這是影像

我想要的是,只要選擇驅動程式選項卡,然后按下它必須列印“選擇的驅動程式選項卡”,然后在將選項卡切換到“車”選項卡時,然后按下它列印的按鈕“已選中”“轎廂”選項卡。
uj5u.com熱心網友回復:
嘗試添加 DefaultTabController,參考:
int _currentIndex = 0;
tabController.addListener(() {
setState(() {
_currentIndex = tabController.index;
});
});
floatingActionButton: FloatingActionButton(
onPressed: () {
if(_currentIndex == 0) print('');
else print('');
},
uj5u.com熱心網友回復:
將您的 Scaffold 包裹在 Builder 中,然后您可以使用 DefaultTabController.of(context).index 檢索選項卡索引
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 2,
child: Builder(builder: (BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Tabs Demo'),
bottom: TabBar(
tabs: [
Tab(icon: Icon(Icons.contacts), text: "Drivers"),
Tab(icon: Icon(Icons.camera_alt), text: "Cars")
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
if(DefaultTabController.of(context)!.index==1)
{
print("drivers");
}
else
print("cars");
print(
'Current Index: ${DefaultTabController.of(context)!.index}');
},),
body: TabBarView(
children: [
Center(child:Text("Driver")) ,
Center(child:Text("Cars")) ,
],
),
);
}
),
)
);
}
}
或者你也可以在 TabBar 中使用 onTap 方法
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
int currentScreen=0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: Text('Flutter Tabs Demo'),
bottom: TabBar(
onTap:(index){
currentScreen=index;
},
tabs: [
Tab(icon: Icon(Icons.contacts), text: "Drivers"),
Tab(icon: Icon(Icons.camera_alt), text: "Cars")
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
if(currentScreen==0)
{
print("drivers");
}
else
print("cars");
},),
body: TabBarView(
children: [
Center(child:Text("Driver")) ,
Center(child:Text("Cars")) ,
],
),
)
) );
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/398581.html
