问题描述
背景故事
我正在为我的高中开发一个应用程序,该应用程序的一个功能我遇到了问题 我正在尝试使用 Twitter API 获取我的高中 user_timeline 的列表视图使用 .
在控制台中显示推文我的研究
YouTube 视频
-
通过编程上瘾者在 Flutter 中显示来自 JSON 的数据:https://www.youtube.com/watch?v=Fo04xk9gIFo
-
12 Flutter 从 API 中获取数据 - Country House:https://www.youtube.com/watch?v=1put849Lhqg
-
详细的 Flutter API 教程 |从 Internet 获取数据:https://www.youtube.com/watch?v=MEqUx3_KrFo&t=964s
-
使用 Flutter 的 HTTP 请求:https://www.youtube.com/watch?v=wr8WsNVxybY&t=372s
-
Flutter 中的 FutureBuilder - 使用 JSON 数据构建列表:https://www.youtube.com/watch?v=EwHMSxSWIvQ&t=75s
代码
twitter_api_service.dart
import 'package:hhsapp/Main_App/Services/Models/Twitter_Model/twitter_model.dart';
import 'package:hhsapp/Main_App/Services/Twitter_API_Services/twitter_api_keys.dart';
import 'package:http/http.dart' as http;
class Twitterapi{
static Future<List<Datum>> getTwitterTimeline()async{
try{
Future twitterRequest = http.get("https://api.twitter.com/2/users/2667176330/tweets",headers: {
'Content-Type': 'application/json','Authorization': 'Bearer $bearerToken'
});
var response = await twitterRequest;
print(response.body);
if (response.statusCode == 200) {
final List<Datum> listTweets = datumFromJson(response.body);
return listTweets;
}
else{
return List<Datum>();
}
} catch(e) {
return List<Datum>();
}
}}
twitter_model.dart
// To parse this JSON data,do
//
// final twitterFeed = twitterFeedFromJson(jsonString);
import 'dart:convert';
TwitterFeed twitterFeedFromJson(String str) => TwitterFeed.fromJson(json.decode(str));
List<Datum> datumFromJson(String str) => List<Datum>.from(json.decode(str).map((x) => Datum.fromJson(x)));
String datumToJson(List<Datum> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
String twitterFeedToJson(TwitterFeed data) => json.encode(data.toJson());
class TwitterFeed {
TwitterFeed({
this.data,this.Meta,});
List<Datum> data;
Meta Meta;
factory TwitterFeed.fromJson(Map<String,dynamic> json) => TwitterFeed(
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),Meta: Meta.fromJson(json["Meta"]),);
Map<String,dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),"Meta": Meta.toJson(),};
}
class Datum {
Datum({
this.id,this.text,});
String id;
String text;
factory Datum.fromJson(Map<String,dynamic> json) => Datum(
id: json["id"],text: json["text"],dynamic> toJson() => {
"id": id,"text": text,};
}
class Meta {
Meta({
this.oldestId,this.newestId,this.resultCount,this.nextToken,});
String oldestId;
String newestId;
int resultCount;
String nextToken;
factory Meta.fromJson(Map<String,dynamic> json) => Meta(
oldestId: json["oldest_id"],newestId: json["newest_id"],resultCount: json["result_count"],nextToken: json["next_token"],dynamic> toJson() => {
"oldest_id": oldestId,"newest_id": newestId,"result_count": resultCount,"next_token": nextToken,};
}
twitter_api_keys.dart
String bearerToken = 'BearerToken Goes Here'; // I have removed the Actual BearerToken for this post
Homepage.dart
import 'package:Flutter/material.dart';
import 'package:hhsapp/Main_App/Navigation/side_drawer.dart';
import 'package:hhsapp/Main_App/Services/Twitter_API_Services/twitter_api_service.dart';
import 'package:hhsapp/Main_App/Services/Models/Twitter_Model/twitter_model.dart';
void main() => runApp((Homepage()));
class Homepage extends StatefulWidget {
@override
_HomepageState createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
List<Datum> Feed;
bool loading;
@override
void initState() {
super.initState();
loading = true;
Twitterapi.getTwitterTimeline().then((listFeed) {
setState(() {
Feed = listFeed;
loading = false;
});
});
}
Widget build(BuildContext context) {
return MaterialApp(debugShowCheckedModeBanner: false,theme: ThemeData(
primaryColor: Colors.redAccent,canvasColor: Colors.white,accentColor: Colors.grey,backgroundColor: Colors.red,),home: Scaffold(appBar: AppBar(title: Text(loading ? 'Loading': 'Datum'),drawer: MainsideDrawer(),body: Container(
color: Colors.white,child: ListView(
children: [
ListTile(title: Text(Twitterapi.getTwitterTimeline().toString()))
],)
),);
}
}
pubspec.yaml
name: hhsapp
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots,like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in Flutter
# build by specifying --build-name and --build-number,respectively.
# In Android,build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS,build-name is used as CFBundleShortVersionString while build-number used as CFBundLeversion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
Flutter:
sdk: Flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons:
webview_Flutter: ^1.0.7
font_awesome_Flutter: ^8.11.0
webFeed:
url_launcher:
http:
cached_network_image:
cloud_firestore: ^0.16.0
firebase_core: ^0.7.0
eva_icons_Flutter: ^2.0.0
jiffy: ^3.0.1
shimmer: ^1.1.1
dev_dependencies:
Flutter_test:
sdk: Flutter
# For information on the generic Dart part of this file,see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
Flutter:
# The following line ensures that the Material Icons font is
# included with your application,so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application,add an assets section,like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants",see
# https://Flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies,see
# https://Flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application,add a fonts section here,# in this "Flutter" section. Each entry in this list should have a
# "family" key with the font family name,and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,# see https://Flutter.dev/custom-fonts/#from-packages
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)