本文全面介绍了Flutter的基础语法和开发流程,包括Dart语言的基本用法、Flutter组件的使用方法以及布局与样式的设置。此外,文章还涵盖了状态管理与事件处理的基本概念和实战项目演练,帮助读者全面掌握Flutter语法。
Flutter是由Google开发的一个用于创建跨平台移动应用的开源UI框架。它能够将一套代码库同时运行在Android和iOS平台,同时还支持Web、桌面应用与嵌入式设备。Flutter的目标是帮助开发者更容易地构建高性能的移动应用,并且拥有丰富的动画、手势支持和自定义能力。
在VS Code中配置Flutter SDK路径:
flutter config --dart-licenses
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer sudo xcodebuild -license
打开命令行工具,输入以下命令验证安装是否成功:
flutter doctor
若输出无任何警告或错误,则安装成功。
Dart是一种强类型语言,这意味着在声明变量时必须指定其类型。
int age = 25; // 整型变量 double height = 1.75; // 浮点型变量 String name = "张三"; // 字符串变量 bool isStudent = true; // 布尔型变量
Dart函数用于执行特定任务,通常返回一个值。定义函数的基本语法如下:
int add(int a, int b) { return a + b; }
Dart是面向对象的语言,支持类和对象的概念。类定义了对象的结构和行为。
class Person { String name; int age; Person(this.name, this.age); void introduce() { print("My name is $name, I am $age years old."); } } void main() { var person = Person("张三", 25); person.introduce(); }
Flutter的应用程序主要由Widget构成。Widget可以被看作是一个自定义的UI元素。以下是几个常用的Widget:
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("Flutter Demo"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text("Hello, Flutter!"), Container( width: 100, height: 100, color: Colors.blue, child: Text( "Container", style: TextStyle(color: Colors.white), ), ), RaisedButton( onPressed: () {}, child: Text("Button"), ), ], ), ), ), ); } }
Flutter提供了多种布局方式,如Row
、Column
、Wrap
等。
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("Flutter Demo"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text("Hello, Flutter!"), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Icon(Icons.star), Icon(Icons.star), Icon(Icons.star), ], ), ], ), ), ), ); } }
可以通过Theme
和ThemeData
来设置全局样式,也可以通过Container
、Text
等Widget的属性来设置局部样式。
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text("Flutter Demo"), ), body: Center( child: Container( padding: EdgeInsets.all(16), decoration: BoxDecoration( color: Colors.blue, borderRadius: BorderRadius.circular(10), ), child: Text( "Hello, Flutter!", style: TextStyle(color: Colors.white, fontSize: 20), ), ), ), ), ); } }
Dart支持多种条件语句,如if
、else if
、else
。
int age = 25; if (age >= 18) { print("成年人"); } else if (age >= 13) { print("青少年"); } else { print("儿童"); }
Dart支持多种循环结构,如for
、while
、do-while
。
// for循环 for (int i = 0; i < 5; i++) { print(i); } // while循环 int n = 0; while (n < 5) { print(n); n++; } // do-while循环 int m = 0; do { print(m); m++; } while (m < 5);
函数定义的基本语法如下:
int add(int a, int b) { return a + b; }
void main() { int result = add(3, 5); print(result); // 输出8 }
Dart支持函数重载。可以通过不同的参数类型或数量来定义多个同名函数。
int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } void main() { int result = add(3, 5); double result2 = add(3.5, 5.5); print(result); // 输出8 print(result2); // 输出9.0 }
函数参数可以是位置参数、命名参数或可选参数。
void greet(String name, [String? title]) { print("Hello, $name!"); if (title != null) { print("Title: $title"); } } void main() { greet("张三"); greet("李四", title: "工程师"); }
函数可以返回一个值,也可以返回多个值通过return
语句。
(int, int) subtract(int a, int b) { int result = a - b; int remainder = a % b; return (result, remainder); } void main() { var (result, remainder) = subtract(10, 3); print("结果: $result"); print("余数: $remainder"); }
在Flutter中,状态管理是非常重要的一个方面。状态管理可以帮助应用更好地响应用户输入和变化。
StatefulWidget
和setState
:这是最基础的状态管理方式。通过StatefulWidget
和State
类进行状态管理。Provider
:这是一个流行的第三方库,用于状态管理和依赖注入。Bloc
:一个用于状态管理的架构模式,通过定义事件和状态来进行状态管理。import 'package:flutter/material.dart'; class CounterWidget extends StatefulWidget { @override _CounterWidgetState createState() => _CounterWidgetState(); } class _CounterWidgetState extends State<CounterWidget> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Counter"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), RaisedButton( onPressed: _incrementCounter, child: Text('Increment'), ), ], ), ), ); } } void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: CounterWidget(), ); } }
在Flutter中,可以使用GestureDetector
、InkWell
等Widget来监听触屏事件。
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("Event Handling"), ), body: Center( child: GestureDetector( onTap: () { print("按钮被点击了"); }, child: Container( width: 200, height: 200, color: Colors.blue, child: Center( child: Text( "点击我", style: TextStyle(color: Colors.white, fontSize: 20), ), ), ), ), ), ), ); } }
在Flutter中,事件处理回调通常使用箭头函数定义。
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("Event Handling"), ), body: Center( child: GestureDetector( onTap: () { print("按钮被点击了"); }, child: Container( width: 200, height: 200, color: Colors.blue, child: Center( child: Text( "点击我", style: TextStyle(color: Colors.white, fontSize: 20), ), ), ), ), ), ), ); } }
响应式编程是一种编程范式,它可以处理变化的数据流。在Flutter中,可以使用Stream
和StreamBuilder
来实现响应式编程。
import 'package:flutter/material.dart'; class CounterBloc { Stream<int> get counterStream { StreamController<int> controller = StreamController<int>(); int counter = 0; controller.add(counter); void increment() { counter++; controller.add(counter); } return controller.stream; } void dispose() { // 释放资源 } } void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { CounterBloc _counterBloc = CounterBloc(); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("Counter"), ), body: StreamBuilder<int>( stream: _counterBloc.counterStream, initialData: 0, builder: (context, snapshot) { if (snapshot.hasData) { return Center( child: Text( "${snapshot.data}", style: TextStyle(fontSize: 30), ), ); } else { return Center( child: CircularProgressIndicator(), ); } }, ), floatingActionButton: FloatingActionButton( onPressed: () { _counterBloc.increment(); }, child: Icon(Icons.add), ), ), ); } @override void dispose() { _counterBloc.dispose(); super.dispose(); } }
初始化项目:使用flutter create
命令创建一个新的Flutter项目。
flutter create my_app cd my_app
修改主文件:修改lib/main.dart
文件。
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'My App', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('My App'), ), body: Center( child: Text('Hello, Flutter!'), ), ); } }
在MyHomePage
中添加一个按钮。
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'My App', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('My App'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), SizedBox(height: 20), RaisedButton( onPressed: _incrementCounter, child: Text('Increment'), ), ], ), ), ); } }
在MyHomePage
中添加一个列表。
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'My App', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('My App'), ), body: ListView( children: <Widget>[ ListTile( title: Text("Item 1"), ), ListTile( title: Text("Item 2"), ), ListTile( title: Text("Item 3"), ), // 更多列表项... ], ), ); } }
在MyHomePage
中集成一个图片资源。
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'My App', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('My App'), ), body: Center( child: Image.asset( 'assets/images/my_image.png', width: 100, height: 100, fit: BoxFit.cover, ), ), ); } }
在MyHomePage
中集成一个网络图片资源。
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'My App', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('My App'), ), body: Center( child: Image.network( 'https://example.com/my_image.png', width: 100, height: 100, fit: BoxFit.cover, ), ), ); } }
在MyHomePage
中集成一个第三方组件,例如flutter_svg
。
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'My App', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('My App'), ), body: Center( child: SvgPicture.asset( 'assets/svg/my_svg.svg', width: 100, height: 100, ), ), ); } }
在pubspec.yaml
文件中添加外部依赖库。
dependencies: flutter: sdk: flutter flutter_svg: ^0.19.0
然后在命令行中运行:
flutter pub get