无法在Flutter中使用DIO消耗API

gzszwxb4  于 2023-06-24  发布在  Flutter
关注(0)|答案(1)|浏览(138)

我试图使用DIO使用API端点,但它没有显示任何数据。当我在Postman上尝试时,端点工作正常,但我不确定哪里出了问题。下面是我的代码:

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:tes2/article.dart';

class ArticleProvider extends ChangeNotifier {
  List<Article> articles = [];
  final Dio dio = Dio();

  Future<List<Article>> getAllArticles() async {
    try {
      const String url = 'https://13.210.163.192:8080/users/public/articles';
      Response response = await dio.get(
        url,
      );
      articles = (response.data['data']['article'] as List)
          .map((e) => Article.fromJson(e))
          .toList();

      return articles;
    } catch (e) {
      rethrow;
    }
  }
}

class Article {
  String? id;
  String? image;
  String? title;
  String? author;
  String? topic;
  int? viewCount;
  int? commentCount;
  String? date;
  bool? saved;

  Article({
    this.id,
    this.image,
    this.title,
    this.author,
    this.topic,
    this.viewCount,
    this.commentCount,
    this.date,
    this.saved,
  });

  Article.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    image = json['image'];
    title = json['title'];
    author = json['author'];
    topic = json['topic'];
    viewCount = json['view_count'];
    commentCount = json['comment_count'];
    date = json['date'];
    saved = json['saved'];
  }
}

class ArticleListScreen extends StatelessWidget {
  const ArticleListScreen({Key? key});

  @override
  Widget build(BuildContext context) {
    // Register ArticleProvider as a provider above the widget tree
    final articleProvider = Provider.of<ArticleProvider>(context);

    // Execute fetchArticles when the widget is built
    articleProvider.getAllArticles();

    return Scaffold(
      appBar: AppBar(
        title: const Text('Daftar Artikel'),
      ),
      body: Consumer<ArticleProvider>(
        builder: (context, articleProvider, _) {
          // Check if the article data has been retrieved
          if (articleProvider.articles.isEmpty) {
            return const Center(child: CircularProgressIndicator());
          }

          // Display the article data
          return ListView.builder(
            itemCount: articleProvider.articles.length,
            itemBuilder: (context, index) {
              return ListTile(
                leading:
                    Image.network(articleProvider.articles[index].image ?? ''),
                title: Text(articleProvider.articles[index].title ?? ''),
                subtitle: Text(articleProvider.articles[index].author ?? ''),
              );
            },
          );
        },
      ),
    );
  }
}

有人能帮帮我吗我被这个错误卡住了,我已经尝试了许多教程,但似乎没有一个工作。我尝试使用的端点是https://13.210.163.192:8080/users/public/articles。谢谢你。

t5fffqht

t5fffqht1#

您需要添加notifyListeners();
在此添加

articles = (response.data['data']['article'] as List)
      .map((e) => Article.fromJson(e))
      .toList();
  // This will notify listeners and cause re-render.
  notifyListeners();
  return articles;

但在您当前的代码中,这可能会导致递归调用。因此也更改以下代码

final articleProvider = Provider.of<ArticleProvider>(context);

final articleProvider = Provider.of<ArticleProvider>(context,listen: false);

**编辑:**我不知道你在哪里创建提供程序。无论您在哪里创建它,都要确保它与此模式相似

runApp(
    MultiProvider(providers: [
      ChangeNotifierProvider(create: (_)=> ArticleProvider())
    ],
      child: const MyApp(),
    )
  );

相关问题