本人最近在学习fluutter 难免会忘记一些常用语法 所以让gpt整理了如下笔记
🧭基础速查(Dart + Flutter)
📌 Dart 基础语法
// 变量
var name = '小白'; // 自动类型推断
String city = '泉州'; // 指定类型
final age = 18; // 运行时常量
const pi = 3.14; // 编译时常量
// 函数
int add(int a, int b) => a + b;
// 类
class Person {
String name;
Person(this.name);
void sayHello() => print('Hello, $name');
}
🧱 常用控件 Widget
控件 | 用途 |
Text() | 显示文字 |
Container() | 布局容器,支持样式、边距等 |
Row() / Column() | 水平/垂直布局 |
ListView() | 可滚动列表 |
Image.asset() / Image.network() | 显示图片 |
ElevatedButton() | 按钮 |
Icon() | 图标 |
Scaffold() | 页面结构,包含 AppBar 等 |
Center() | 居中 |
Expanded() | 弹性布局 |
Stack() | 堆叠布局 |
示例:
Scaffold(
appBar: AppBar(title: Text('首页')),
body: Center(child: Text('Hello 小白')),
);
🧠 状态管理(State)
Stateful Widget
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
int counter = 0;
void increment() {
setState(() => counter++);
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Text('$counter'),
ElevatedButton(
onPressed: increment,
child: Text('加一'),
)
],
);
}
}
🌐 路由导航
// 定义路由表
MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => HomePage(),
'/about': (context) => AboutPage(),
},
);
// 跳转
Navigator.pushNamed(context, '/about');
🎨 样式与主题
Text(
'你好 Flutter',
style: TextStyle(
fontSize: 20,
color: Colors.blue,
fontWeight: FontWeight.bold,
),
);
Container(
margin: EdgeInsets.all(10),
padding: EdgeInsets.symmetric(horizontal: 20),
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.circular(10),
),
);
📦 包管理(pubspec.yaml)
dependencies:
flutter:
sdk: flutter
http: ^0.13.0
provider: ^6.0.0
安装依赖:
flutter pub get
🖥 桌面支持配置(Windows/Linux/macOS)
flutter config --enable-linux-desktop
flutter config --enable-windows-desktop
flutter config --enable-macos-desktop
flutter create .
flutter run -d windows # macos/linux 也可以
🔧 调试与构建
flutter run # 运行应用
flutter build windows # 构建桌面程序
flutter build apk # 构建安卓包
flutter build web # 构建网页版
flutter build windows --release # 使用Release模式构建桌面程序
🧩 实用插件推荐
插件 | 用途 |
provider | 状态管理 |
http | 网络请求 |
shared_preferences | 本地存储 |
flutter_svg | 加载 SVG 图片 |
url_launcher | 打开网页/电话/邮件等 |
file_picker | 文件选择(桌面支持) |