Flutter动态堆栈管理插件deferred_indexed_stack的使用

Flutter 动态堆栈管理插件 deferred_indexed_stack 的使用

这个插件是 IndexedStack 的一个替代品,支持延迟加载并提供一些额外的自定义功能。

特性

  • 延迟初始化特定标签页,直到用户打开它们。
  • 显式设置某些标签页的延迟时间。
  • 在需要时显式初始化某些标签页。

使用方法

首先,在 pubspec.yaml 文件中添加依赖:

dependencies:
  deferred_indexed_stack: ^0.0.4

然后在你的 Dart 文件中导入该包:

import 'package:deferred_indexed_stack/deferred_indexed_stack.dart';

接下来,我们来看一个完整的示例代码:

import 'package:deferred_indexed_stack/deferred_indexed_stack.dart';
import 'package:flutter/material.dart';

// 假设你已经有一个 DashboardTab 组件
import 'dashboard_tab.dart';
// 假设你已经有一个 SomeLayout 组件
import 'some_layout.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // 这个小部件是你的应用的根组件
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _controller = DeferredIndexedStackController();
  var _index = 0;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      bottomNavigationBar: BottomNavigationBar(
        showUnselectedLabels: true,
        onTap: (value) => setState(() {
          _index = value;
        }),
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.accessibility_new_sharp),
            label: "Home",
            backgroundColor: Colors.deepPurple,
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.access_alarms),
            label: "Tab A",
            backgroundColor: Colors.deepPurple,
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.ac_unit_outlined),
            label: "Tab B",
            backgroundColor: Colors.deepPurple,
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.align_horizontal_left_outlined),
            label: "Tab C",
            backgroundColor: Colors.deepPurple,
          ),
        ],
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Expanded(
            child: DeferredIndexedStack(
              controller: _controller,
              index: _index,
              children: [
                // 这个标签页不被延迟初始化
                DashboardTab(stackController: _controller),

                // 这个标签页会在用户打开时初始化
                // 或者通过 _controller.initChildById('tab_a') 初始化
                // 或者通过 _controller.initChildAt(1) 初始化
                const DeferredTab(
                  id: 'tab_a',
                  child: SomeLayout(
                    name: 'Tab A',
                    text: "Deferred tab A",
                  ),
                ),

                // 这个标签页会在用户打开时初始化
                // 或者在 10 秒后初始化
                // 或者通过 _controller.initChildById('tab_b') 初始化
                // 或者通过 _controller.initChildAt(2) 初始化
                const DeferredTab(
                  id: 'tab_b',
                  deferredFor: Duration(seconds: 10),
                  child: SomeLayout(
                    name: 'Tab B',
                    text: "Init on button click or 10 seconds",
                  ),
                ),

                // 这个标签页会在用户打开时初始化
                const DeferredTab(
                  child: SomeLayout(
                    name: 'Tab C',
                    text: "This tab initializes when opened",
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

更多关于Flutter动态堆栈管理插件deferred_indexed_stack的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter动态堆栈管理插件deferred_indexed_stack的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter中使用deferred_indexed_stack插件进行动态堆栈管理的代码示例。deferred_indexed_stack插件允许你延迟加载和卸载堆栈中的页面,从而提高应用的性能和资源利用效率。

首先,确保你已经在pubspec.yaml文件中添加了deferred_indexed_stack依赖:

dependencies:
  flutter:
    sdk: flutter
  deferred_indexed_stack: ^最新版本号

然后,运行flutter pub get来安装依赖。

接下来,是一个简单的示例,展示了如何使用DeferredIndexedStack来管理堆栈中的页面:

import 'package:flutter/material.dart';
import 'package:deferred_indexed_stack/deferred_indexed_stack.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Deferred Indexed Stack Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  final List<Widget> _pages = [
    PageOne(),
    PageTwo(),
    PageThree(),
  ];

  int _currentIndex = 0;

  void _navigateToIndex(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Deferred Indexed Stack Demo'),
      ),
      body: DeferredIndexedStack(
        index: _currentIndex,
        builder: (context, index) {
          return _pages[index];
        },
        // Optionally, you can customize the loading placeholder
        loadingBuilder: (context, index) {
          return Center(
            child: CircularProgressIndicator(),
          );
        },
        // Optionally, you can specify the number of pages to keep alive around the current index
        keepAliveCount: 1,
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Page One',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.settings),
            label: 'Page Two',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.help),
            label: 'Page Three',
          ),
        ],
        currentIndex: _currentIndex,
        onTap: _navigateToIndex,
      ),
    );
  }
}

class PageOne extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('Page One'),
    );
  }
}

class PageTwo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('Page Two'),
    );
  }
}

class PageThree extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('Page Three'),
    );
  }
}

在这个示例中:

  1. DeferredIndexedStack用于创建堆栈,其中页面会根据_currentIndex动态加载和卸载。
  2. builder函数根据索引返回相应的页面。
  3. loadingBuilder函数提供了一个加载占位符(在这个例子中是CircularProgressIndicator),当页面正在加载时显示。
  4. keepAliveCount参数指定了在当前页面周围要保留多少个页面(在这个例子中是1个),这有助于优化性能和资源使用。
  5. BottomNavigationBar用于在页面之间导航。

这样,你就能够利用deferred_indexed_stack插件在Flutter应用中实现动态堆栈管理。

回到顶部