你瞅啥呢

2025-04-18 flutter计数器示例代码解析(deepseek)

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @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
  State<MyHomePage> createState() => _MyHomePageState();
}

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

  void _incrementCounter() {
    setState(() {_counter++;});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

这是一个典型的 Flutter 计数器应用示例,展示了 Flutter 的核心开发模式。以下是对代码的逐层解析:


1. 应用入口 (main)

void main() {
  runApp(const MyApp());
}
  • 作用:Flutter 应用的唯一入口函数

  • runApp():将根组件挂载到渲染树

  • 最佳实践:始终使用 const 构造函数优化性能


2. 根组件 (MyApp)

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,  // 启用 Material 3 设计
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
配置项作用说明
MaterialApp 应用骨架,提供 Material Design 基础能力(导航、主题等)
colorScheme 基于种子色(deepPurple)自动生成完整配色方案
useMaterial3 启用 Material 3 设计语言(圆角、新组件样式等)
home 指定首页组件,可替换为 routes 路由系统

3. 首页组件 (MyHomePage)

(1) 状态类定义

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;  // 不可变属性

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
  • StatefulWidget 特点:

    • 由不可变的配置部分(MyHomePage)和可变的状态部分(_MyHomePageState)组成

    • 适合需要动态更新的界面

(2) 状态管理

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;  // 可变状态

  void _incrementCounter() {
    setState(() {  // 状态更新触发器
      _counter++;  // 实际状态变更
    });
  }
}
  • setState 机制

    1. 修改状态变量(_counter

    2. 触发组件重建(build 方法重新执行)

    3. 框架智能计算差异并局部更新 UI

(3) 页面布局

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      title: Text(widget.title),  // 使用父组件传递的title
    ),
    body: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Text('You have pushed...'),  // 静态文本
          Text('$_counter',  // 动态文本
            style: Theme.of(context).textTheme.headlineMedium,
          ),
        ],
      ),
    ),
    floatingActionButton: FloatingActionButton(
      onPressed: _incrementCounter,  // 点击回调
      tooltip: 'Increment',  // 长按提示
      child: const Icon(Icons.add),
    ),
  );
}
组件关键功能
Scaffold 提供 Material 标准页面框架(AppBar/Body/FAB 等)
Theme.of(context) 获取当前主题数据,实现样式统一
Column 垂直布局,mainAxisAlignment 控制主轴(垂直)对齐方式
FloatingActionButton 悬浮按钮,Material Design 的典型交互元素

4. 核心工作机制

sequenceDiagram
    participant User
    participant UI
    participant State

    User->>UI: 点击FAB按钮
    UI->>State: 调用_incrementCounter()
    State->>State: _counter++ 
    State->>UI: setState()触发重建
    UI->>UI: 重建Text('$_counter')

5. 进阶学习建议

  1. 状态管理升级

    // 使用Riverpod替代setState
    final counterProvider = StateProvider((ref) => 0);
  2. 布局深度

    • 尝试用 ListView.builder 替代 Column 实现滚动列表

    • 学习 Flex 和 Expanded 实现复杂布局

  3. 主题扩展

    theme: ThemeData(
      textTheme: TextTheme(
        displayLarge: TextStyle(fontFamily: 'Roboto'),
    ),
  4. 国际化的title

    title: AppLocalizations.of(context)!.homeTitle,

这个示例虽然简单,但涵盖了 Flutter 最核心的三大概念:组件化状态管理响应式编程,是理解 Flutter 开发模式的绝佳起点。

posted @ 2025-04-18 14:57  叶乘风  阅读(53)  评论(0)    收藏  举报