【问题标题】:Flutter Wordpress : The getter 'length' was called on null. Receiver: null Tried calling: lengthFlutter Wordpress:在 null 上调用了 getter 'length'。接收方:null 尝试调用:长度
【发布时间】:2023-04-03 01:55:01
【问题描述】:

我的 Flutter 代码有一个小问题。我正在尝试使用颤振包“flutter_wordpress”在应用程序中显示我网站上的帖子。如果我现在使用“https://demo.wp-api.org”作为示例代码中的网站,则帖子将正常显示。但是,如果我在帖子中使用自己的 Wordpress 网站地址,则会出现错误The getter 'length' was called on null. Receiver: null Tried calling: length

import 'details_page.dart';

class LandingPage extends StatelessWidget {

 wp.WordPress wordPress = wp.WordPress(
 baseUrl: 'https://pluto.faithlux.eu/wp-json/wp/v2/posts',
);

  _launchUrl(String link) async {
    if (await canLaunch(link)) {
      await launch(link);
    } else {
      throw 'Cannot launch $link';
    }
  }


  _fetchPosts() {
    Future<List<wp.Post>> posts = wordPress.fetchPosts(
        postParams: wp.ParamsPostList(
          context: wp.WordPressContext.view,
          pageNum: 1,
          perPage: 5,
        ),
        fetchAuthor: true,
        fetchFeaturedMedia: true,
        fetchComments: true
    );

    return posts;
  }

  _getPostImage(wp.Post post) {
    if (post.featuredMedia == null) {
      return SizedBox();
    }
    return Image.network(post.featuredMedia.sourceUrl);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: FutureBuilder(
          future: _fetchPosts(),
          builder: (BuildContext context, AsyncSnapshot<List<wp.Post>> snapshot) {
            if (snapshot.connectionState == ConnectionState.none) {
              return Container();
            }
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: CircularProgressIndicator(),
              );
            }
            return ListView.builder(
              itemCount: snapshot.data.length ?? 0,
              itemBuilder: (context, index) {
                wp.Post post = snapshot.data[index];
                return InkWell(
                  onTap: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => DetailsPage(post)
                        )
                    );
                  },
                  child: Padding(
                    padding: const EdgeInsets.all(5.0),
                    child: Card(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Column(
                          children: <Widget>[
                            _getPostImage(post),
                            SizedBox(height: 10,),
                            Text(
                              post.title.rendered.toString(),
                              style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 20
                              ),
                            ),
                            SizedBox(height: 15,),
                            Html(
                              data: post.excerpt.rendered.toString(),
                              onLinkTap: (String link) {
                                _launchUrl(link);
                              },
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Text(post.date.toString().replaceAll('T', ' ')),
                                Text(post.author.name),
                              ],
                            )
                          ],
                        ),
                      ),
                    ),
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }}

【问题讨论】:

    标签: wordpress flutter


    【解决方案1】:

    您网站上的帖子的 REST API 是否按预期工作?


    这似乎是您的网站而不是应用程序的后端问题。这个 URL 返回什么? :


     https://"yoursite".com/wp-json/wp/v2/posts
    

    【讨论】:

    • 嗨 :) 感谢您的快速回答!该页面实际上显示了一个错误。但我现在才注意到它,因为链接昨天工作了很短的时间。错误显示:{"status":"error","error":"MISSING_AUTHORIZATION_HEADER","code":"401","error_description":"Authorization header not received. Either authorization header was not sent or it was removed by your server due to security reasons."}。你知道如何解决这个问题吗?
    • 哦,我明白了,我在上面的问题中发布了错误的代码。我会改的。
    【解决方案2】:

    为我工作:

    1. 在您的 Flutter 应用中,实例化 WordPress,并将身份验证器设置为 JWT
        wp.WordPress wordPress = wp.WordPress(
            baseUrl: 'https://your-website-domain-only',
            authenticator: wp.WordPressAuthenticator.JWT,
            adminName: '',
            adminKey: '',
          );
    
    1. 在您的 wordpress 网站上,安装 https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/ 插件。不要忘记在 wp-config.php 中集成您的 JWT 密钥:
    define('JWT_AUTH_SECRET_KEY', 'your-secret-key');
    
    1. 回到您的 Flutter 应用程序,您需要在获取帖子之前使用管理员凭据进行身份验证,如下所示:
        Future<List<wp.Post>> _fetchPosts() async {
          Future<wp.User> response = wordPress.authenticateUser(
            username: 'your admin username',
            password: 'your admin password',
          );
    
          try {
            wp.User user = await response;
            print("User is: ");
            print(user);
          } catch (e) {
            print('Failed to fetch user: $e');
          }
    
          List<wp.Post> posts = await wordPress.fetchPosts(
            postParams: wp.ParamsPostList(
              context: wp.WordPressContext.view,
              pageNum: 1,
              perPage: 10,        
            ),
            fetchAuthor: true,
            fetchFeaturedMedia: true,
            fetchCategories: true
          );
    
          return posts;
        }
    

    【讨论】:

      猜你喜欢
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多