如何在 flutter 中设置初始选项卡
How to Set Initial Tab in flutter
我希望每当我 运行 我的应用程序时,它都应该移动到选项卡 A,但默认情况下它会移动到第一个选项卡,该选项卡名为选项卡 B。
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: Scaffold(
appBar: AppBar(
title: Text("Tab Bar"),
bottom:
TabBar(tabs: [Tab(child: Text('B')), Tab(child: Text('A'))]),
),
body: TabBarView(children: [
Center(
child: Text("this is to be second tab"),
),
Center(
child: Text("this is to be first tab"),
),
]),
)),
);
}
}
DefaultTabController
有一个 initialIndex
属性 默认设置为 0
。
在您的情况下,由于您有两个 Tab
,因此您需要将 initialIndex
属性 设置为 1
。
我以您的代码为例添加了一个演示:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 2,
// set initial index to 1
initialIndex: 1,
child: Scaffold(
appBar: AppBar(
title: Text("Tab Bar"),
bottom:
TabBar(tabs: [Tab(child: Text('B')), Tab(child: Text('A'))]),
),
body: TabBarView(children: [
Center(
child: Text("this is to be second tab"),
),
Center(
child: Text("this is to be first tab"),
),
]),
)),
);
}
}
我希望每当我 运行 我的应用程序时,它都应该移动到选项卡 A,但默认情况下它会移动到第一个选项卡,该选项卡名为选项卡 B。
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: Scaffold(
appBar: AppBar(
title: Text("Tab Bar"),
bottom:
TabBar(tabs: [Tab(child: Text('B')), Tab(child: Text('A'))]),
),
body: TabBarView(children: [
Center(
child: Text("this is to be second tab"),
),
Center(
child: Text("this is to be first tab"),
),
]),
)),
);
}
}
DefaultTabController
有一个 initialIndex
属性 默认设置为 0
。
在您的情况下,由于您有两个 Tab
,因此您需要将 initialIndex
属性 设置为 1
。
我以您的代码为例添加了一个演示:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 2,
// set initial index to 1
initialIndex: 1,
child: Scaffold(
appBar: AppBar(
title: Text("Tab Bar"),
bottom:
TabBar(tabs: [Tab(child: Text('B')), Tab(child: Text('A'))]),
),
body: TabBarView(children: [
Center(
child: Text("this is to be second tab"),
),
Center(
child: Text("this is to be first tab"),
),
]),
)),
);
}
}