<aside> 💡 作者链接:https://space.bilibili.com/442752399 视频链接:https://www.bilibili.com/video/BV1ZL411s7ez/ 源码地址:https://gitee.com/liu__yang/learn_flutter

</aside>

// 创建崭新项目
flutter create app
// 进入目录
cd app
// 运行
flutter run

Hello案例(基本入门)

lib/main.dart是整个程序的启动类

Flutter中,每个东西都是一个组件


import "package:flutter/material.dart";

// 主启动类
void main(List<String> args) {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  // 构造函数
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 直接返回一个APP
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.amber),  // 设置主题颜色为琥珀色
      home: Scaffold(
        appBar: AppBar(title: const Text("Title")),  // 设置标题栏文本为"Title"
        body: const Center(
          child: Text("Hello", style: TextStyle(color: Colors.amber),)  // 设置文本为"Hello",颜色为琥珀色
        ),
      ),
    );
  }
}

点击计数器(有状态组件)

import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.deepPurple),
      home: HomePage(title: "测试Bar"),
    );
  }
}

class HomePage extends StatefulWidget {
  // 构造函数传递参数,自动装配到this.title当中去
  HomePage({Key? key, required this.title}) : super(key: key);
  final title;

  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  int count = 10;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 通过widget.title获取上一个组件的属性
      appBar: AppBar(title: Text(widget.title)),
      body: Center(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text("你已经点击的次数"),
          Text('$count', style: Theme.of(context).textTheme.headlineLarge)
        ],
      )),
      floatingActionButton: FloatingActionButton(
        // 如果传递参数,应该使用 匿名函数的方法
        onPressed: () => _increase(3),
        child: const Icon(Icons.add),
      ),
    );
  }

  void _increase(int n) {
    setState(() {
      count += n;
    });
  }
}

爱心配对(第三方包的使用)

import "package:english_words/english_words.dart";
import "package:flutter/material.dart";

void main(List<String> args) {
  return runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData(primarySwatch: Colors.deepPurple), home: HomePage());
  }
}

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return HomePageState();
  }
}

class HomePageState extends State<HomePage> {
  final words = <WordPair>[];
  final favoriteWords = <String>[];

  @override
  Widget build(BuildContext context) {
    words.addAll(generateWordPairs().take(10));

    return Scaffold(
      appBar: AppBar(
        title: const Text("爱心配对❤"),
        actions: [IconButton(onPressed: _goToloved, icon: Icon(Icons.list))],
      ),
      body: _buildList(),
    );
  }

	// 导航栏跳转
  void _goToloved() {
    Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext) {
      final Iterable<ListTile> titles = favoriteWords.map((word) {
        return ListTile(title: Text(word));
      });
      return Scaffold(
          appBar: AppBar(title: const Text("喜欢的单词")),
          body: ListView(
            children: titles.toList(),
          ));
    }));
  }

	// 建立无限长的列表
  Widget _buildList() {
    return ListView.builder(itemBuilder: (content, item) {
      if (item.isOdd) {
        return const Divider(
          thickness: 2,
          color: Colors.deepPurpleAccent,
        );
      } else {
        int index = item ~/ 2;
        if (index >= words.length) {
          words.addAll(generateWordPairs().take(10));
        }
        String ws = words[index].asCamelCase;
        return ListTile(
          title: Text("$ws"),
          trailing: _buildLoveIcon(ws),
          onTap: () => _pressed(ws),
          // IconButton(onPressed: ()=> _pressed(), Icons: Icons.favorite_border, color: Colors.red,)
        );
      }
    });
  }

	// 根据状态建立图标
  Widget _buildLoveIcon(String ws) {
    if (favoriteWords.contains(ws)) {
      return const Icon(Icons.favorite, color: Colors.red);
    } else {
      return const Icon(Icons.favorite_border);
    }
  }

  // 点击事件
  void _pressed(String ws) {
    // 改变状态时,必须加上setState
    setState(() {
      if (favoriteWords.contains(ws)) {
        favoriteWords.remove(ws);
      } else {
        favoriteWords.add(ws);
      }
    });
  }
}

自动生成的模板

import 'package:flutter/material.dart';

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

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

  // This widget is the root of your application.
  @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),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}