Виджет DefaultTabController
Виджет DefaultTabController оборачивает экран с вкладками,
чтобы не создавать
TabController
вручную.
Число вкладок задают в length,
начальный индекс - в initialIndex,
поддерево с TabBar и TabBarView - в child.
Синтаксис
DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(tabs: [Tab(text: 'abcde'), Tab(text: '12345')]),
),
body: TabBarView(children: [Text('11111'), Text('22222')]),
),
)
Параметры
| Параметр | Описание |
|---|---|
length |
Сколько вкладок у TabBar и TabBarView.
|
initialIndex |
Какая вкладка открыта при старте. |
child |
Виджеты, которые читают TabController из контекста.
|
Пример
Давайте обернём экран с двумя вкладками:
import 'package:flutter/material.dart';
void main()
{
runApp(
MaterialApp(
home: DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
Tab(text: 'abcde'),
Tab(text: '12345'),
],
),
),
body: TabBarView(
children: [
Center(child: Text('11111')),
Center(child: Text('22222')),
],
),
),
),
),
);
}
TabBar и TabBarView делят один TabController автоматически.
Пример
Давайте откроем вторую вкладку при старте:
import 'package:flutter/material.dart';
void main()
{
runApp(
MaterialApp(
home: DefaultTabController(
length: 2,
initialIndex: 1,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [Tab(text: 'abcde'), Tab(text: '12345')],
),
),
body: TabBarView(
children: [
Center(child: Text('11111')),
Center(child: Text('22222')),
],
),
),
),
),
);
}
Сразу виден экран '22222' и подсвечена вторая вкладка.
Смотрите также
-
класс
TabController,
которыйDefaultTabControllerсоздаёт внутри -
виджет
TabBar,
который берёт controller изDefaultTabController -
виджет
TabBarView,
который листает те же вкладки -
виджет
Tab,
которым описывают каждую вкладку