Flutter 中的 StatefulBuilder 小部件

本文是关于 Flutter 中的 StatefulBuilder 小部件。我将介绍小部件的基础知识,然后检查一个在实际中使用它的完整示例。、StatefulBuilder 小部件可以在这些区域的状态发生变化时仅重建某些小区域而无需付出太多努力。这提高了应用程序的性能。

StatefulBuilder({
  Key? key, 
  required StatefulWidgetBuilder builder
r})

builder 函数有两个参数:context和一个用于在状态改变时触发重建的函数:

builder: (context, setInnerState) => SomeWidget(/* ...*/)

另一个注意事项是,您应该将保持状态的变量保留在构建器函数之外。为了更清楚,请参阅下面的完整示例。

例子

预览

我们要构建的示例应用程序是一种计数器应用程序。它包含一个按钮和一个位于红色圆圈内的文本小部件。每按一次按钮,文本小部件中的数字就会增加一个单位。我们将只使用StatefulBuilder小部件来实现这一点。你不会看到任何StatefulWidget

以下是它的工作原理:

image-20220517232306547

**注意:**如果您使用的是 Safari,此演示视频可能无法正常播放或根本无法播放。请改用 Chrome、Edge、Firefox 或其他网络浏览器。

编码

带有解释的完整代码:

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: '大前端之旅',
      theme: ThemeData(
        primarySwatch: Colors.amber,
      ),
      home: const HomePage(),
    );
  }
}

// StatelessWidget is used here
class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // This is the number shown in the red circle
    // It represents state and stays outside the builder function
    int count = 0;
    return Scaffold(
      appBar: AppBar(title: const Text('大前端之旅')),
      body: Padding(
        padding: const EdgeInsets.all(30),
        child: Center(
          // Implement StatefulBuilder
          child: StatefulBuilder(
            builder: (context, setInnerState) => Column(
              children: [
                Container(
                  width: 300,
                  height: 300,
                  decoration: const BoxDecoration(
                      color: Colors.red, shape: BoxShape.circle),
                  child: Center(
                    // Display the number
                    child: Text(
                      count.toString(),
                      style: const TextStyle(fontSize: 80, color: Colors.white),
                    ),
                  ),
                ),
                const SizedBox(
                  height: 20,
                ),
                // This button is used to crease the number
                ElevatedButton.icon(
                    onPressed: () {
                      // Call setInnerState function
                      setInnerState(() => count++);
                    },
                    icon: const Icon(Icons.add),
                    label: const Text('Increase By One')),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

结论

您已经了解了有关 StatefulBuilder 小部件的几乎所有内容。这在 Flutter 中并不是不可替代的东西,但在实现部分应用程序时会给你更多的选择。

猜你喜欢

转载自blog.csdn.net/qq_39132095/article/details/124840046