Flutter User Manual

Basic Concepts

Widget Introduction

Widget is the basic building block of Flutter UI. In Flutter, everything is a widget, including layout, padding, align, etc. Widgets describe what their view should look like given the current configuration and state.

Flutter widgets are immutable. When you need to change the UI, you need to recreate the widget or use StatefulWidget with state management. Widgets can be nested to form a widget tree, and Flutter efficiently compares the old and new widget trees, only rendering the parts that actually changed.

Common widgets include: Text, Image, Icon, Container, Row/Column, Stack, ListView, etc.

StatelessWidget and StatefulWidget

StatelessWidget is a widget without state, suitable for static UI displays like text and images. Defining a StatelessWidget only requires implementing the build method, returning the widget tree to render.

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text('Hello Flutter');
  }
}

StatefulWidget is a widget with state, suitable for scenarios requiring dynamic UI updates like counters and forms. StatefulWidget needs to be used with State, calling setState to notify Flutter to rebuild when state changes.

class Counter extends StatefulWidget {
  @override
  State<Counter> createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int _count = 0;
  
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Count: $_count'),
        ElevatedButton(
          onPressed: () => setState(() => _count++),
          child: Text('Increment'),
        ),
      ],
    );
  }
}

Layout Basics

Linear Layout

Row and Column are the most commonly used linear layout widgets. Row arranges child widgets horizontally, Column arranges them vertically. Use MainAxisAlignment and CrossAxisAlignment to control alignment.

Row(
  mainAxisAlignment: MainAxisAlignment.spaceBetween,
  children: [
    Icon(Icons.home),
    Text('Home'),
    Icon(Icons.settings),
  ],
)

Stack Layout

Stack is used to create stacked layouts, placing widgets on top of another widget. Positioned is used to position children in a Stack.

Stack(
  children: [
    Container(color: Colors.blue, width: 200, height: 200),
    Positioned(
      top: 10,
      left: 10,
      child: Text('Overlay'),
    ),
  ],
)

List Layout

ListView is the most commonly used list widget, suitable for long lists. ListView.builder is suitable for large datasets with lazy loading. ListView.separated can add separators.

ListView.builder(
  itemCount: items.length,
  itemBuilder: (context, index) => ListTile(
    title: Text(items[index]),
  ),
)

State Management

setState

setState is the most basic state management method, suitable for simple local state. In StatefulWidget, calling setState triggers widget rebuild.

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

Provider

Provider is one of Flutter's recommended state management solutions. Through Provider, you can share state in the widget tree to avoid passing it down layer by layer.

// Define ChangeNotifier
class CounterModel extends ChangeNotifier {
  int _count = 0;
  int get count => _count;
  
  void increment() {
    _count++;
    notifyListeners();
  }
}

// Use Provider
ChangeNotifierProvider(
  create: (_) => CounterModel(),
  child: Consumer<CounterModel>(
    builder: (context, model, _) => Text('${model.count}'),
  ),
)

Other State Management Solutions

For complex applications, there are also Riverpod, GetX, and BLoC. Riverpod is an upgrade to Provider, offering better performance and type safety. GetX integrates state management, routing, and dependency injection. BLoC manages state using event streams, suitable for large complex applications.

Network Requests

HTTP Package

Use the http package to make simple HTTP requests:

import 'package:http/http.dart' as http;

final response = await http.get(Uri.parse('https://api.example.com/data'));

Dio

Dio is a powerful HTTP client, supporting interceptors, request cancellation, file uploads, etc:

import 'package:dio/dio.dart';

final dio = Dio();
final response = await dio.get('https://api.example.com/data');

Local Storage

SharedPreferences

Used for storing simple key-value data:

import 'package:shared_preferences/shared_preferences.dart';

final prefs = await SharedPreferences.getInstance();
await prefs.setString('name', 'Flutter');
final name = prefs.getString('name');

SQLite

For structured data, use the sqflite package:

import 'package:sqflite/sqflite.dart';

final db = await openDatabase('my.db');
await db.insert('users', {'name': 'Flutter'});

Flutter uses Navigator for page navigation. Basic operations include Navigator.push (push new page), Navigator.pop (return), Navigator.pushReplacement (replace current page), etc.

Named routing is the recommended routing management method:

// Define routes
MaterialApp(
  routes: {
    '/home': (context) => HomePage(),
    '/detail': (context) => DetailPage(),
  },
);

// Navigate
Navigator.pushNamed(context, '/detail');

Building and Publishing

Android Release

Use keytool to generate signing key:

keytool -genkey -v -keystore my-key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias my-key

Configure signing in android/app/build.gradle, then run in project root:

flutter build apk --release

iOS Release

Configure signing certificate and provisioning profile in Xcode, then run:

flutter build ios --release

Note that iOS release requires an Apple Developer account and corresponding certificates.