如何将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 => truewhen registering them in your WordPress theme’sfunctions.phpor 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_storageto 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
metaparameter in your API calls (and make sure the fields are registered as REST-accessible in WordPress). - Pagination: For large post lists, use the
pageandper_pagequery parameters in thefetchPostsmethod.
内容的提问来源于stack exchange,提问作者user11106201

