Flutter学习1 - Android开发者快速上手

1、对应关系

  • 概念对应关系
Android Flutter
页面 Activity和Fragment Widget
视图 View Widget
页面跳转 Intent Navigater
网络库 okHttp http
数据存储 SharedPreference和SQLite shared_preferences和sqflite
  • 布局对应关系
Android Flutter
布局文件 xml Widget
线性布局 LinearLayout Row和Column widget
相对布局 RelativeLayout 组合使用Column、Row和Stack Widget
文本框 TextView text
输入框 EditText TextField
  • 滚动列表对应关系
Android Flutter
布局文件 xml Widget
滚动视图 ScrollView ListView
列表 ListView ListView
列表 RecyclerView ListView.builder

2、快速上手布局开发

(1)更新 Widget 状态

dart 复制代码
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(
        primarySwatch: Colors.blue,
      ),
      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> {
  String tips = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Text(tips),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _updateTips,
        tooltip: 'Update',
        child: const Icon(Icons.add),
      ),
    );
  }

  //更新布局 widgets
  //类似android中 setText
  void _updateTips() {
    //我们无法改变widget,因为 Flutter 中 widget 是不可变的
    //但是可以通过 setState 改变 widget状态
    setState(() {
      tips = "快速上手 Flutter";
    });
  }
}
  • 在body中添加一个Text,其取值为 tips
  • 按钮的点击事件 _updateTips() 中,通过 setState() 改变 tips 的值,从而更新 widget 状态

该示例类似于 android 中的 textView.setText(tips)

(2)布局中添加/删除一个 Widget

dart 复制代码
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: 'muke flutter',
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      home: const MyHomePage(title: 'muke learning'),
    );
  }
}

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

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  bool _toggle = true;

  get _dyWidget => _toggle ? const Text("Widget 1") : const Text("Widget 2");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: _dyWidget,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _updateWidget,
        tooltip: 'Update',
        child: const Icon(Icons.add),
      ),
    );
  }

  //在布局中添加/删除一个 widget
  //类似安卓中 addView、removeView
  void _updateWidget() {
    setState(() {
      _toggle = !_toggle;
    });
  }
}
  • body中添加一个 Text,这个 Text 会根据 _toggle 的值变换,Text("Widget 1")或Text("Widget 2")
  • 按钮点击事件 _updateWidget() 通过 setState() 更改 _toggle 的值,从而实现更换 widget 效果

(3)创建自定义 Widget

dart 复制代码
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: 'muke flutter',
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      home: const MyHomePage(title: 'muke learning'),
    );
  }
}

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

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: const Center(
        child: TipsWidget(),
      ),
    );
  }
}

//自定义 Widget
class TipsWidget extends StatelessWidget {
  const TipsWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return const Text("自定义 Widget");
  }
}
  • 自定义 TipsWidget,然后添加至 body 中

(4)添加一个滚动列表

dart 复制代码
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: 'muke flutter',
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      home: const MyHomePage(title: 'muke learning'),
    );
  }
}

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

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  get _listView => ListView(
        children: const [
          Text("AAA"),
          Text("BBB"),
          Text("CCC"),
          Text("DDD"),
          Text(
            "EEE",
            style: TextStyle(fontSize: 230),
          )
        ],
      );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body:  Center(
        child: _listView,
      ),
    );
  }
}
  • 添加一个 ListView,当超出屏幕时就会滚动

3、手势事件处理

(1)监听 Widget 手势

dart 复制代码
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: 'muke flutter',
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      home: const MyHomePage(title: 'muke learning'),
    );
  }
}

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 _count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text("click me : $_count"),
          onPressed: () {
            setState(() {
              _count++;
            });
          },
        ),
      ),
    );
  }
}
  • 点击按钮实现 +1

(2)GestureDetector手势监听

dart 复制代码
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: 'muke flutter',
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      home: const MyHomePage(title: 'muke learning'),
    );
  }
}

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 _count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: GestureDetector(
          child: Text("click me : $_count"),
          onTap: () {
            setState(() {
              _count++;
            });
          },
          onLongPress: () {
            setState(() {
              _count = 0;
            });
          },
        ),
      ),
    );
  }
}
  • GestureDetetor 只是对 Text 添加了一个手势监听,没有按钮样式
  • onTap():单机时,加一
  • onLongPress():长按时,清零

4、进阶

(1)异步 UI

(2)页面跳转

(3)工程结构和资源文件

(4)网络请求

(5)数据存储

相关推荐
迷雾漫步者2 小时前
Flutter组件————FloatingActionButton
前端·flutter·dart
南宫生4 小时前
力扣-图论-17【算法学习day.67】
java·学习·算法·leetcode·图论
拭心4 小时前
Google 提供的 Android 端上大模型组件:MediaPipe LLM 介绍
android
sanguine__5 小时前
Web APIs学习 (操作DOM BOM)
学习
数据的世界017 小时前
.NET开发人员学习书籍推荐
学习·.net
带电的小王7 小时前
WhisperKit: Android 端测试 Whisper -- Android手机(Qualcomm GPU)部署音频大模型
android·智能手机·whisper·qualcomm
coder_pig7 小时前
📝小记:Ubuntu 部署 Jenkins 打包 Flutter APK
flutter·ubuntu·jenkins
四口鲸鱼爱吃盐7 小时前
CVPR2024 | 通过集成渐近正态分布学习实现强可迁移对抗攻击
学习
梦想平凡7 小时前
PHP 微信棋牌开发全解析:高级教程
android·数据库·oracle
元争栈道7 小时前
webview和H5来实现的android短视频(短剧)音视频播放依赖控件
android·音视频