You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Flutter应用接入WordPress?REST API代码修改位置咨询

Flutter + WordPress REST API 对接指南(数据增删改查)

Hey there! Let me break down exactly how to connect your Flutter app to a WordPress site using its built-in REST API, including where to place your code for fetching, pushing, and updating data. I’ll keep this practical with real code examples you can adapt.

First: Prep Work

WordPress enables the REST API by default (since version 4.7), so you don’t need any extra plugins for basic post operations. That said:

  • If you’re working with custom post types, make sure you set show_in_rest => true when registering them in your WordPress theme’s functions.php or a custom plugin.
  • For write operations (create/update), you’ll need authentication—we’ll use Basic Auth here for simplicity (but note: in production, use JWT or OAuth2 for better security).

Step 1: Add Dependencies to Flutter

First, add the http package to your pubspec.yaml—it’s the simplest way to make HTTP calls:

dependencies:
  flutter:
    sdk: flutter
  http: ^1.1.0

Run flutter pub get to install it.

Step 2: Organize Your API Code (Where to Put It!)

Don’t clutter your UI widgets with API logic—create a dedicated service class to handle all WordPress API interactions. This keeps your code clean and maintainable.

Create a new file called wordpress_api_service.dart:

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

class WordPressApiService {
  // Replace with your WordPress site URL
  final String baseUrl = 'https://your-wordpress-site.com/wp-json/wp/v2';
  // Replace with your WordPress admin credentials (store securely in production!)
  final String username = 'your-admin-username';
  final String password = 'your-admin-password';

  // Encode credentials for Basic Auth
  String get _basicAuth => 'Basic ${base64Encode(utf8.encode('$username:$password'))}';

  // 1. Fetch Posts (Read Operation)
  Future<List<dynamic>> fetchPosts() async {
    final response = await http.get(Uri.parse('$baseUrl/posts'));
    
    if (response.statusCode == 200) {
      return json.decode(response.body);
    } else {
      throw Exception('Failed to load posts: ${response.reasonPhrase}');
    }
  }

  // 2. Create a Post (Push Operation)
  Future<dynamic> createPost(Map<String, dynamic> postData) async {
    final response = await http.post(
      Uri.parse('$baseUrl/posts'),
      headers: {
        'Authorization': _basicAuth,
        'Content-Type': 'application/json',
      },
      body: json.encode(postData),
    );

    if (response.statusCode == 201) {
      return json.decode(response.body);
    } else {
      throw Exception('Failed to create post: ${json.decode(response.body)['message']}');
    }
  }

  // 3. Update a Post (Modify Operation)
  Future<dynamic> updatePost(int postId, Map<String, dynamic> updatedData) async {
    final response = await http.put(
      Uri.parse('$baseUrl/posts/$postId'),
      headers: {
        'Authorization': _basicAuth,
        'Content-Type': 'application/json',
      },
      body: json.encode(updatedData),
    );

    if (response.statusCode == 200) {
      return json.decode(response.body);
    } else {
      throw Exception('Failed to update post: ${json.decode(response.body)['message']}');
    }
  }
}

Step 3: Use the Service in Your UI

Now you can call these methods from your Flutter widgets. Here’s an example of a screen that loads posts, lets you create a new post, and could be extended to update posts:

import 'package:flutter/material.dart';
import 'wordpress_api_service.dart';

class WordPressPostsScreen extends StatefulWidget {
  const WordPressPostsScreen({super.key});

  @override
  State<WordPressPostsScreen> createState() => _WordPressPostsScreenState();
}

class _WordPressPostsScreenState extends State<WordPressPostsScreen> {
  final WordPressApiService _apiService = WordPressApiService();
  List<dynamic> _posts = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    // Load posts when the screen initializes
    _loadPosts();
  }

  Future<void> _loadPosts() async {
    try {
      final posts = await _apiService.fetchPosts();
      setState(() {
        _posts = posts;
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      // Show error to user
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Oops: $e')),
      );
    }
  }

  // Example: Create a sample post
  Future<void> _createSamplePost() async {
    try {
      final newPost = await _apiService.createPost({
        'title': 'Flutter-Created Post',
        'content': 'This post was sent straight from my Flutter app! 🚀',
        'status': 'publish', // Use 'draft' if you don't want to publish immediately
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Post created! ID: ${newPost['id']}')),
      );
      // Refresh posts list after creation
      _loadPosts();
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to create post: $e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('WordPress x Flutter')),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : ListView.builder(
              itemCount: _posts.length,
              itemBuilder: (context, index) {
                final post = _posts[index];
                return ListTile(
                  title: Text(post['title']['rendered']),
                  subtitle: Text(post['excerpt']['rendered']),
                  onTap: () {
                    // Add update logic here (e.g., open an edit screen)
                    // _updatePost(post['id']);
                  },
                );
              },
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: _createSamplePost,
        child: const Icon(Icons.add),
      ),
    );
  }
}

Key Notes for Production

  • Security: Never hardcode credentials in your app! Use packages like flutter_secure_storage to store sensitive data, or implement JWT authentication instead of Basic Auth.
  • Error Handling: Expand the error handling to cover network timeouts, invalid responses, and permission issues.
  • Custom Fields: If you need to work with custom post fields, use the meta parameter in your API calls (and make sure the fields are registered as REST-accessible in WordPress).
  • Pagination: For large post lists, use the page and per_page query parameters in the fetchPosts method.

内容的提问来源于stack exchange,提问作者user11106201

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:16:41