Flutter 初识: Material Design 布局和结构控件

MaterialApp

MaterialApp 是 Flutter 中的主要应用小部件,提供了一个 Material Design 风格的应用框架。它封装了导航、主题、路由和许多其他配置选项

属性解析

const MaterialApp({
    super.key,
    this.navigatorKey,
    this.scaffoldMessengerKey,
    this.home,
    Map<String, WidgetBuilder> this.routes = const <String, WidgetBuilder>{},
    this.initialRoute,
    this.onGenerateRoute,
    this.onGenerateInitialRoutes,
    this.onUnknownRoute,
    this.onNavigationNotification,
    List<NavigatorObserver> this.navigatorObservers = const <NavigatorObserver>[],
    this.builder,
    this.title = '',
    this.onGenerateTitle,
    this.color,
    this.theme,
    this.darkTheme,
    this.highContrastTheme,
    this.highContrastDarkTheme,
    this.themeMode = ThemeMode.system,
    this.themeAnimationDuration = kThemeAnimationDuration,
    this.themeAnimationCurve = Curves.linear,
    this.locale,
    this.localizationsDelegates,
    this.localeListResolutionCallback,
    this.localeResolutionCallback,
    this.supportedLocales = const <Locale>[Locale('en', 'US')],
    this.debugShowMaterialGrid = false,
    this.showPerformanceOverlay = false,
    this.checkerboardRasterCacheImages = false,
    this.checkerboardOffscreenLayers = false,
    this.showSemanticsDebugger = false,
    this.debugShowCheckedModeBanner = true,
    this.shortcuts,
    this.actions,
    this.restorationScopeId,
    this.scrollBehavior,
    @Deprecated(
      'Remove this parameter as it is now ignored. '
      'MaterialApp never introduces its own MediaQuery; the View widget takes care of that. '
      'This feature was deprecated after v3.7.0-29.0.pre.'
    )
    this.useInheritedMediaQuery = false,
    this.themeAnimationStyle,
  })
  • navigatorKey (GlobalKey?): 全局键,用于控制导航。
  • scaffoldMessengerKey (GlobalKey?): 用于控制 ScaffoldMessenger 的全局键。
  • home (Widget?): 应用程序启动时显示的主屏幕小部件。
  • routes (Map<String, WidgetBuilder>): 定义命名路由及其对应的小部件。
  • initialRoute (String?): 应用程序启动时显示的初始路由。
  • onGenerateRoute (RouteFactory?): 当导航到某个命名路由时,如果该路由未在 routes 表中定义,则调用此回调生成路由。
  • onGenerateInitialRoutes (InitialRouteListFactory?): 提供一个函数来生成初始路由列表。
  • onUnknownRoute (RouteFactory?): 当导航到未知路由时调用的回调函数。
  • onNavigationNotification (NavigationNotificationCallback?): 当接收到导航通知时调用的回调函数。
  • navigatorObservers (List): 导航观察者列表,用于监控导航事件。
  • builder (TransitionBuilder?): 在导航小部件构建之后调用的函数,可以用于添加额外的小部件,如 Overlay。
  • title (String): 应用程序的标题。
  • onGenerateTitle (GenerateAppTitle?): 生成应用程序标题的回调函数。
  • color (Color?): 应用程序的主要颜色,在 Android 上用于任务管理器中的应用程序条的背景色。
  • theme (ThemeData?): 应用程序的主题数据。
  • darkTheme (ThemeData?): 应用程序的暗色主题数据。
  • highContrastTheme (ThemeData?): 高对比度主题数据。
  • highContrastDarkTheme (ThemeData?): 高对比度暗色主题数据。
  • themeMode (ThemeMode): 主题模式(系统、浅色或深色)。
  • themeAnimationDuration (Duration): 主题切换动画的持续时间。
  • themeAnimationCurve (Curve): 主题切换动画的曲线。
  • locale (Locale?): 应用程序的语言环境。
  • localizationsDelegates (Iterable?): 本地化代理列表。
  • localeListResolutionCallback (LocaleListResolutionCallback?): 回调函数,用于从设备支持的语言环境列表中选择应用程序的语言环境。
  • localeResolutionCallback (LocaleResolutionCallback?): 回调函数,用于从设备支持的单一语言环境中选择应用程序的语言环境。
  • supportedLocales (Iterable): 支持的语言环境列表。
  • debugShowMaterialGrid (bool): 是否在调试模式下显示 Material 网格指示器。
  • showPerformanceOverlay (bool): 是否显示性能叠加层。
  • checkerboardRasterCacheImages (bool): 是否显示瓦片缓存图像的棋盘格。
  • checkerboardOffscreenLayers (bool): 是否显示离屏层的棋盘格。
  • showSemanticsDebugger (bool): 是否显示语义调试器。
  • debugShowCheckedModeBanner (bool): 是否在调试模式下显示右上角的 “DEBUG” 横幅。
  • shortcuts (Map<LogicalKeySet, Intent>?): 全局快捷键映射。
  • actions (Map<Type, Action>?): 全局操作映射。
  • restorationScopeId (String?): 恢复范围 ID。
  • scrollBehavior (ScrollBehavior?): 滚动行为。
  • useInheritedMediaQuery (bool): 已弃用参数,不再使用。
  • themeAnimationStyle (ThemeAnimationStyle?): 主题动画样式。

示例

class WidgetPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      darkTheme: ThemeData.dark(),
      themeMode: ThemeMode.system,
      home: HomeScreen(),
      routes: {
        '/second': (context) => SecondScreen(),
      },
      initialRoute: '/',
      onGenerateRoute: (settings) {
        if (settings.name == '/third') {
          return MaterialPageRoute(builder: (context) => ThirdScreen());
        }
        return null;
      },
      onUnknownRoute: (settings) {
        return MaterialPageRoute(builder: (context) => UnknownScreen());
      },
      supportedLocales: [
        Locale('en', 'US'),
        Locale('es', 'ES'),
      ],
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home Screen'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Home Screen'),
            ElevatedButton(
              onPressed: () {
                Navigator.pushNamed(context, '/second');
              },
              child: Text('Go to Second Screen'),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.pushNamed(context, '/third');
              },
              child: Text('Go to Third Screen'),
            ),
          ],
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Screen'),
      ),
      body: Center(
        child: Text('Second Screen'),
      ),
    );
  }
}

class ThirdScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Third Screen'),
      ),
      body: Center(
        child: Text('Third Screen'),
      ),
    );
  }
}

class UnknownScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Unknown Screen'),
      ),
      body: Center(
        child: Text('Unknown Screen'),
      ),
    );
  }
}

在这里插入图片描述

 
&nsbp;

Scaffold

Scaffold 是 Flutter 中用于实现基本的 Material Design 布局结构的小部件。它提供了一个默认的页面框架,包括应用栏、抽屉、浮动操作按钮和底部导航栏等元素。

属性解析

const Scaffold({
    super.key,
    this.appBar,
    this.body,
    this.floatingActionButton,
    this.floatingActionButtonLocation,
    this.floatingActionButtonAnimator,
    this.persistentFooterButtons,
    this.persistentFooterAlignment = AlignmentDirectional.centerEnd,
    this.drawer,
    this.onDrawerChanged,
    this.endDrawer,
    this.onEndDrawerChanged,
    this.bottomNavigationBar,
    this.bottomSheet,
    this.backgroundColor,
    this.resizeToAvoidBottomInset,
    this.primary = true,
    this.drawerDragStartBehavior = DragStartBehavior.start,
    this.extendBody = false,
    this.extendBodyBehindAppBar = false,
    this.drawerScrimColor,
    this.drawerEdgeDragWidth,
    this.drawerEnableOpenDragGesture = true,
    this.endDrawerEnableOpenDragGesture = true,
    this.restorationId,
  })
  • appBar (PreferredSizeWidget?): 页面顶部的应用栏。
  • body (Widget?): Scaffold 的主要内容区域。
  • floatingActionButton (Widget?): 浮动操作按钮,通常用于突出显示的主操作。
  • floatingActionButtonLocation (FloatingActionButtonLocation?): 控制浮动操作按钮的位置。
  • floatingActionButtonAnimator (FloatingActionButtonAnimator?): 浮动操作按钮的动画效果。
  • persistentFooterButtons (List?): 固定在底部的一组按钮。
  • persistentFooterAlignment (AlignmentDirectional): 固定按钮的对齐方式,默认为 AlignmentDirectional.centerEnd。
  • drawer (Widget?): 左侧滑出的抽屉菜单。
  • onDrawerChanged (DrawerCallback?): 当抽屉打开或关闭时的回调。
  • endDrawer (Widget?): 右侧滑出的抽屉菜单。
  • onEndDrawerChanged (DrawerCallback?): 当右侧抽屉打开或关闭时的回调。
  • bottomNavigationBar (Widget?): 底部导航栏,通常用于应用程序的主要导航。
  • bottomSheet (Widget?): 固定在底部的面板,可以覆盖其他内容。
  • backgroundColor (Color?): Scaffold 的背景颜色。
  • resizeToAvoidBottomInset (bool?): 内容是否因避开键盘而调整大小。
  • primary (bool): 是否包含顶部的系统状态栏,默认为 true。
  • drawerDragStartBehavior (DragStartBehavior): 抽屉拖动开始行为,默认为 DragStartBehavior.start。
  • extendBody (bool): 主体是否延伸到屏幕底部导航栏后面,默认为 false。
  • extendBodyBehindAppBar (bool): 主体是否延伸到应用栏后面,默认为 false。
  • drawerScrimColor (Color?): 抽屉打开时遮罩的颜色。
  • drawerEdgeDragWidth (double?): 从边缘开始拖动以打开抽屉的触发距离。
  • drawerEnableOpenDragGesture (bool): 是否可以通过手势打开左侧抽屉,默认为 true。
  • endDrawerEnableOpenDragGesture (bool): 是否可以通过手势打开右侧抽屉,默认为 true。
  • restorationId (String?): 用于状态恢复的 ID。

示例

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _selectedIndex = 0;

  static const List<Widget> _widgetOptions = <Widget>[
    Text('Home Page',
        style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),
    Text('Business Page',
        style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),
    Text('School Page',
        style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),
  ];

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Scaffold Example'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            label: 'Business',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            label: 'School',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}

在这里插入图片描述

 
 

AppBar

AppBar 是 Flutter 中用于显示在 Scaffold 顶部的应用栏。它可以包含标题、导航按钮、动作按钮等元素,并提供了许多自定义选项。

属性解析

AppBar({
    super.key,
    this.leading,
    this.automaticallyImplyLeading = true,
    this.title,
    this.actions,
    this.flexibleSpace,
    this.bottom,
    this.elevation,
    this.scrolledUnderElevation,
    this.notificationPredicate = defaultScrollNotificationPredicate,
    this.shadowColor,
    this.surfaceTintColor,
    this.shape,
    this.backgroundColor,
    this.foregroundColor,
    this.iconTheme,
    this.actionsIconTheme,
    this.primary = true,
    this.centerTitle,
    this.excludeHeaderSemantics = false,
    this.titleSpacing,
    this.toolbarOpacity = 1.0,
    this.bottomOpacity = 1.0,
    this.toolbarHeight,
    this.leadingWidth,
    this.toolbarTextStyle,
    this.titleTextStyle,
    this.systemOverlayStyle,
    this.forceMaterialTransparency = false,
    this.clipBehavior,
  })
  • leading (Widget?): 显示在应用栏左侧的小部件,通常是返回按钮或菜单按钮。
  • automaticallyImplyLeading (bool): 是否根据当前路由自动添加返回按钮或抽屉图标,默认为 true。
  • title (Widget?): 显示在应用栏中间的主要内容,通常是文本标题。
  • actions (List?): 显示在应用栏右侧的一组小部件,通常是操作按钮。
  • flexibleSpace (Widget?): 一个可伸缩的小部件,通常用于实现复杂的应用栏布局,如背景图像或渐变色。
  • bottom (PreferredSizeWidget?): 应用栏底部的扩展区域,通常是 TabBar。
  • elevation (double?): 应用栏的阴影高度。
  • scrolledUnderElevation (double?): 当滚动到此应用栏下方时的阴影高度。
  • notificationPredicate (ScrollNotificationPredicate): 决定何时触发 - scrolledUnderElevation 的回调,默认为 defaultScrollNotificationPredicate。
  • shadowColor (Color?): 阴影颜色。
  • surfaceTintColor (Color?): 表面色调颜色。
  • shape (ShapeBorder?): 应用栏的形状及边框样式。
  • backgroundColor (Color?): 应用栏的背景颜色。
  • foregroundColor (Color?): 应用栏上内容的前景颜色(如文字和图标)。
  • iconTheme (IconThemeData?): 应用栏图标的主题样式。
  • actionsIconTheme (IconThemeData?): 应用栏操作按钮图标的主题样式。
  • primary (bool): 应用栏是否显示在顶部状态栏之下,默认为 true。
  • centerTitle (bool?): 是否将标题居中对齐。
  • excludeHeaderSemantics (bool): 是否排除头部的语义信息,默认为 false。
  • titleSpacing (double?): 标题与应用栏两侧的间距。
  • toolbarOpacity (double): 工具栏的透明度,默认为 1.0。
  • bottomOpacity (double): 底部扩展区域的透明度,默认为 1.0。
  • toolbarHeight (double?): 工具栏的高度。
  • leadingWidth (double?): leading 小部件的宽度。
  • toolbarTextStyle (TextStyle?): 工具栏中所有文本的默认样式。
  • titleTextStyle (TextStyle?): 标题的文本样式。
  • systemOverlayStyle (SystemUiOverlayStyle?): 系统状态栏样式(如状态栏图标和文字的颜色)。
  • forceMaterialTransparency (bool): 强制应用栏为透明背景,默认为 false。

示例

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.menu),
          onPressed: () {
            // 打开左侧抽屉
          },
        ),
        title: Text('AppBar Example'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.search),
            onPressed: () {
              // 执行搜索操作
            },
          ),
          IconButton(
            icon: Icon(Icons.more_vert),
            onPressed: () {
              // 打开更多选项菜单
            },
          ),
        ],
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Colors.blue, Colors.purple],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
          ),
        ),
        bottom: TabBar(
          tabs: [
            Tab(icon: Icon(Icons.home), text: 'Home'),
            Tab(icon: Icon(Icons.business), text: 'Business'),
            Tab(icon: Icon(Icons.school), text: 'School'),
          ],
        ),
        elevation: 10.0,
        shadowColor: Colors.grey,
        backgroundColor: Colors.blueAccent,
        centerTitle: true,
        toolbarHeight: 70.0,
      ),
      body: TabBarView(
        children: [
          Center(child: Text('Home content goes here')),
          Center(child: Text('Business content goes here')),
          Center(child: Text('School content goes here')),
        ],
      ),
    );
  }
}

在这里插入图片描述

 
 

BottomNavigationBar

BottomNavigationBar 是 Flutter 中用于实现底部导航栏的小部件,通常用于在应用程序的不同页面之间进行导航。它可以包含多个导航项,并提供了许多自定义选项

属性解析

BottomNavigationBar({
    super.key,
    required this.items,
    this.onTap,
    this.currentIndex = 0,
    this.elevation,
    this.type,
    Color? fixedColor,
    this.backgroundColor,
    this.iconSize = 24.0,
    Color? selectedItemColor,
    this.unselectedItemColor,
    this.selectedIconTheme,
    this.unselectedIconTheme,
    this.selectedFontSize = 14.0,
    this.unselectedFontSize = 12.0,
    this.selectedLabelStyle,
    this.unselectedLabelStyle,
    this.showSelectedLabels,
    this.showUnselectedLabels,
    this.mouseCursor,
    this.enableFeedback,
    this.landscapeLayout,
    this.useLegacyColorScheme = true,
  }) 
  • items (List): 导航栏中的项目列表,每个项目包含图标和标签。
  • onTap (ValueChanged?): 当某个导航项被点击时调用的回调函数,传递被点击项的索引。
  • currentIndex (int): 当前选中的导航项的索引,默认为 0。
  • elevation (double?): 导航栏的阴影高度。
  • type (BottomNavigationBarType?): 导航栏的类型,可以是 fixed(固定)或 shifting(移动)。
  • fixedColor (Color?): 已弃用,请使用 selectedItemColor 替代。
  • backgroundColor (Color?): 导航栏的背景颜色。
  • iconSize (double): 导航项图标的大小,默认为 24.0。
  • selectedItemColor (Color?): 选中项的颜色。
  • unselectedItemColor (Color?): 未选中项的颜色。
  • selectedIconTheme (IconThemeData?): 选中项图标的主题样式。
  • unselectedIconTheme (IconThemeData?): 未选中项图标的主题样式。
  • selectedFontSize (double): 选中项标签的字体大小,默认为 14.0。
  • unselectedFontSize (double): 未选中项标签的字体大小,默认为 12.0。
  • selectedLabelStyle (TextStyle?): 选中项标签的文本样式。
  • unselectedLabelStyle (TextStyle?): 未选中项标签的文本样式。
  • showSelectedLabels (bool?): 是否显示选中项的标签。
  • showUnselectedLabels (bool?): 是否显示未选中项的标签。
  • mouseCursor (MouseCursor?): 鼠标悬停时显示的光标。
  • enableFeedback (bool?): 是否启用点击反馈。
  • landscapeLayout (BottomNavigationBarLandscapeLayout?): 在横向布局下的样式。
  • useLegacyColorScheme (bool): 是否使用旧版颜色方案,默认为 true。

示例

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _selectedIndex = 0;

  static const List<Widget> _widgetOptions = <Widget>[
    Text('Home Page',
        style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),
    Text('Business Page',
        style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),
    Text('School Page',
        style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),
  ];

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BottomNavigationBar Example'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            label: 'Business',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            label: 'School',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        unselectedItemColor: Colors.grey,
        onTap: _onItemTapped,
        backgroundColor: Colors.blueAccent,
      ),
    );
  }
}

在这里插入图片描述

 
 

Drawer

Drawer 是 Flutter 中用于实现侧边栏菜单的小部件,通常从屏幕的左侧滑出。它允许你在应用中添加导航项、用户信息或其他自定义内容。

属性解析

 const Drawer({
    super.key,
    this.backgroundColor,
    this.elevation,
    this.shadowColor,
    this.surfaceTintColor,
    this.shape,
    this.width,
    this.child,
    this.semanticLabel,
    this.clipBehavior,
  })
  • backgroundColor (Color?): 抽屉的背景颜色。
  • elevation (double?): 抽屉的阴影高度。
  • shadowColor (Color?): 阴影的颜色。
  • surfaceTintColor (Color?): 表面色调颜色。
  • shape (ShapeBorder?): 抽屉的形状及边框样式。
  • width (double?): 抽屉的宽度。
  • child (Widget?): 抽屉的主要内容部分。
  • semanticLabel (String?): 用于语义化描述抽屉的标签。
  • clipBehavior (Clip?): 设置裁剪行为。

示例

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Drawer Example'),
      ),
      drawer: Drawer(
        backgroundColor: Colors.white,
        elevation: 16.0,
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            UserAccountsDrawerHeader(
              accountName: Text("John Doe"),
              accountEmail: Text("johndoe@example.com"),
              currentAccountPicture: CircleAvatar(
                backgroundImage:
                    NetworkImage("https://via.placeholder.com/150"),
              ),
            ),
            ListTile(
              leading: Icon(Icons.home),
              title: Text('Home'),
              onTap: () {
                // Handle the action here
                Navigator.pop(context); // Close the drawer
              },
            ),
            ListTile(
              leading: Icon(Icons.business),
              title: Text('Business'),
              onTap: () {
                // Handle the action here
                Navigator.pop(context); // Close the drawer
              },
            ),
            ListTile(
              leading: Icon(Icons.school),
              title: Text('School'),
              onTap: () {
                // Handle the action here
                Navigator.pop(context); // Close the drawer
              },
            ),
          ],
        ),
      ),
      body: Center(
        child: Text('Content goes here'),
      ),
    );
  }
}

在这里插入图片描述

 
 

TabBar

TabBar 是 Flutter 中用于实现选项卡导航的小部件,它通常与 TabBarView 一起使用,以在应用程序中创建标签页布局。

属性解析

const TabBar({
    super.key,
    required this.tabs,
    this.controller,
    this.isScrollable = false,
    this.padding,
    this.indicatorColor,
    this.automaticIndicatorColorAdjustment = true,
    this.indicatorWeight = 2.0,
    this.indicatorPadding = EdgeInsets.zero,
    this.indicator,
    this.indicatorSize,
    this.dividerColor,
    this.dividerHeight,
    this.labelColor,
    this.labelStyle,
    this.labelPadding,
    this.unselectedLabelColor,
    this.unselectedLabelStyle,
    this.dragStartBehavior = DragStartBehavior.start,
    this.overlayColor,
    this.mouseCursor,
    this.enableFeedback,
    this.onTap,
    this.physics,
    this.splashFactory,
    this.splashBorderRadius,
    this.tabAlignment,
  })
  • tabs (List): 选项卡列表,每个选项卡通常是一个 Tab 小部件。
  • controller (TabController?): 控制选择和动画效果的控制器。
  • isScrollable (bool): 如果为 true,则选项卡可以滚动,否则选项卡将均匀分布,默认为 false。
  • padding (EdgeInsetsGeometry?): 选项卡周围的填充边距。
  • indicatorColor (Color?): 指示器的颜色。
  • automaticIndicatorColorAdjustment (bool): 是否自动调整指示器颜色以适应当前主题,默认为 true。
  • indicatorWeight (double): 指示器的高度,默认为 2.0。
  • indicatorPadding (EdgeInsetsGeometry): 指示器的边距,默认为 EdgeInsets.zero。
  • indicator (Decoration?): 自定义指示器的装饰。
  • indicatorSize (TabBarIndicatorSize?): 指示器的大小,可以是 tab(匹配选项卡宽度)或 label(匹配标签宽度)。
  • dividerColor (Color?): 在选项卡之间绘制的分隔线的颜色。
  • dividerHeight (double?): 分隔线的高度。
  • labelColor (Color?): 选中项标签的颜色。
  • labelStyle (TextStyle?): 选中项标签的文本样式。
  • labelPadding (EdgeInsetsGeometry?): 选中项标签的填充边距。
  • unselectedLabelColor (Color?): 未选中项标签的颜色。
  • unselectedLabelStyle (TextStyle?): 未选中项标签的文本样式。
  • dragStartBehavior (DragStartBehavior): 拖动开始行为,默认为 DragStartBehavior.start。
  • overlayColor (MaterialStateProperty<Color?>?): 选项卡的覆盖颜色。
  • mouseCursor (MouseCursor?): 鼠标悬停时显示的光标。
  • enableFeedback (bool?): 是否启用点击反馈。
  • onTap (ValueChanged?): 当某个选项卡被点击时调用的回调函数,传递被点击项的索引。
  • physics (ScrollPhysics?): 选项卡栏的滚动物理属性。
  • splashFactory (InteractiveInkFeatureFactory?): 用于生成水波纹效果的工厂。
  • splashBorderRadius (BorderRadiusGeometry?): 水波纹效果的圆角半径。
  • tabAlignment (TabAlignment?): 标签对齐方式。

示例

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        appBar: AppBar(
          title: Text('TabBar Example'),
          bottom: TabBar(
            tabs: [
              Tab(icon: Icon(Icons.home), text: "Home"),
              Tab(icon: Icon(Icons.business), text: "Business"),
              Tab(icon: Icon(Icons.school), text: "School"),
            ],
            labelColor: Colors.amber,
            unselectedLabelColor: Colors.black,
            indicatorColor: Colors.amber,
          ),
        ),
        body: TabBarView(
          children: [
            Center(child: Text('Home Page')),
            Center(child: Text('Business Page')),
            Center(child: Text('School Page')),
          ],
        ),
      ),
    );
  }
}

在这里插入图片描述

 
 

TabBarView

TabBarView 是 Flutter 中用于与 TabBar 配合使用的小部件,用于显示对应于每个选项卡的内容页面

属性解析

const TabBarView({
    super.key,
    required this.children,
    this.controller,
    this.physics,
    this.dragStartBehavior = DragStartBehavior.start,
    this.viewportFraction = 1.0,
    this.clipBehavior = Clip.hardEdge,
  })
  • children (List): 所有选项卡对应的内容页面列表。
  • controller (TabController?): 控制选项卡和页面切换的控制器,通常与 TabBar 共用一个控制器。
  • physics (ScrollPhysics?): 页面滚动的物理属性,例如是否允许用户滚动以及滚动时的行为。
  • dragStartBehavior (DragStartBehavior): 拖动开始行为,默认为 DragStartBehavior.start。
  • viewportFraction (double): 每个页面在视口中的占比,默认值为 1.0。
  • clipBehavior (Clip): 设置裁剪行为,默认为 Clip.hardEdge。

示例

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        appBar: AppBar(
          title: Text('TabBar Example'),
          bottom: TabBar(
            tabs: [
              Tab(icon: Icon(Icons.home), text: "Home"),
              Tab(icon: Icon(Icons.business), text: "Business"),
              Tab(icon: Icon(Icons.school), text: "School"),
            ],
            labelColor: Colors.amber,
            unselectedLabelColor: Colors.black,
            indicatorColor: Colors.amber,
          ),
        ),
        body: TabBarView(
          children: [
            Center(child: Text('Home Page')),
            Center(child: Text('Business Page')),
            Center(child: Text('School Page')),
          ],
        ),
      ),
    );
  }
}

在这里插入图片描述

 
 

  • 22
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值