Flutter Twitter (X) Clone: Render Real Tweets in a Dart App

- Real data, not mock JSON: the app calls your proxy, the proxy calls
/twitter/user/last_tweets(20 posts per page, newest first) with theX-API-Keyheader and returns a slim JSON list plushas_next_pageandnext_cursor. - Never ship the key in the app: values passed with
--dart-defineare compile-time constants inside the binary. The proxy holds the key and an allow-list of accounts. - Reposts hide the media: reading only top-level
extendedEntitiesshows media on 39.1% of posts; also readingretweeted_tweetraises it to 57.3% (179 of 237 reposts carry media inside the original). - Trim on the server: the median raw tweet was 8,053 bytes; the proxy's slim shape is 945 bytes, about 157.3 KB vs 18.5 KB per 20-post page on a phone.
- Dedupe by id: 60 of 915 fetched rows repeated an id already seen, so the
ListViewkeeps aSet<String>of ids. Keep ids asString: on Flutter web anintloses precision past 53 bits. - Cost: $0.15 per 1,000 tweets on TwitterAPI.io ($0.003 per full page) against $0.005 per post read on the official X API, about 33x less per 1,000 tweets.
This guide is the Flutter and Dart version of the clone. If you are building the web version with React or Next.js, the sibling guide on building a Twitter clone covers that stack; this page stays on Dart models, Flutter widgets and the mobile constraints that come with them (binary secrets, payload size on cellular data, image aspect ratios on a narrow screen).
Search for a Flutter Twitter clone and you find polished UI projects whose timelines are filled with the app's own users or with mock JSON. That is fine for practicing layouts, but the first thing people ask after building one is how to show real tweets. The answer has three parts: an API that returns real timelines, a server-side proxy so the key never ships inside the app, and a widget tree designed around what real tweets actually contain.
To get that last part right we measured it. We pulled 855 recent posts from 10 public organization timelines (including @FlutterDev and @dart_lang) and counted how often each TweetCard component is needed, how media is nested, how big the payloads are, and how pagination behaves. Every number below comes from that study, and every code block on this page uses the real response fields.
57.3% of 855 organization posts (collected in 2026), versus 39.1% if a clone reads only top-level extendedEntities
What the open-source Flutter Twitter clones give you, and what they leave out
The widely forked reference is Fwitter by TheAlphamerc (github.com/TheAlphamerc/flutter_twitter_clone). Per its README and repository page, it is MIT-licensed, has about 4.2k stars and 1.1k forks, and is built on Firebase: firebase_auth, the Realtime Database (with a separate Firestore branch) and Firebase Storage, with provider in its dependency list. It covers sign-in, a home feed, composing, replies, retweets with comments, profiles, notifications, search and direct messages. The repository lists no releases.
The second family is course projects that build the same app on Appwrite with Riverpod (a freeCodeCamp video course and a paid course follow that stack). There are also commercial templates sold on code marketplaces. All of them share one design: the posts are written by the app's own users into the app's own database.
What none of them do: render real X posts. The feed widgets are built against an in-house schema (a FeedModel with a few fields), so the first real tweet with a repost, a four-image grid or a link card breaks the layout or simply drops content. That is the gap this page fills: keep whichever UI project you like, and replace its data layer with real timelines and a model shaped by real payloads.
Architecture: Flutter app, a small proxy, and the timeline endpoint
The app never talks to api.twitterapi.io directly. It calls GET /feed?user=NASA&cursor= on a proxy you run. The proxy adds the X-API-Key header, calls /twitter/user/last_tweets, converts each tweet to a slim card shape and returns tweets, has_next_page and next_cursor.
Why not put the key in the app? Anything compiled into a Flutter build ships to every user. A key passed with --dart-define becomes a compile-time constant, and a string in source or in an asset file is just as readable once someone unpacks the app. Whoever extracts it can spend your credits. A proxy also gives you three things the app cannot do safely: an allow-list of accounts the feed may show, a short cache so a thousand app opens do not each pay for the same page, and server-side trimming of the payload.
Which endpoint. Per the TwitterAPI.io reference for /twitter/user/last_tweets, the call takes userName or userId (the docs recommend userId as more stable), a cursor that is an empty string on the first page, and includeReplies (default false). It returns up to 20 tweets per page, newest first, in data.tweets, the pinned tweet in data.pin_tweet, and has_next_page plus next_cursor at the top level of the response, not inside data. Pass the cursor back unchanged.
For a search-style feed (a hashtag, a keyword, several accounts at once) the same proxy can call /twitter/tweet/advanced_search with a query such as from:FlutterDev OR from:dart_lang and queryType=Latest; that response puts tweets, has_next_page and next_cursor at the top level. The Dart side does not change, because the proxy returns the same slim shape either way. Reads need no X account and no OAuth.
Step 1: the proxy that holds the key and trims each tweet
The complete proxy is the Python example at the end of this page: standard-library HTTP server plus requests, about 120 lines. It does four jobs. It refuses any account not in ALLOWED. It unwraps reposts: when a tweet has retweeted_tweet, the card draws the original post and shows "Flutter reposted" above it. It takes the visible text with displayTextRange, which drops the trailing t.co link that points at the attached media. And it reduces media, cards and counters to the fields a widget reads.
Why trimming matters on a phone. Across our sample the median tweet object was 8,053 bytes as JSON (90th percentile 15,339, largest 59,856, because a repost or quote embeds a whole second tweet with its own author object). The slim card shape had a median of 945 bytes (90th percentile 1,151). For a 20-post page that is roughly 157.3 KB versus 18.5 KB, a 89.8% reduction over the whole sample, before any compression.
Link cards are the heavy part. A link preview card arrives as a binding_values list with about two dozen keys (several image sizes, color palettes, alt text). The proxy keeps title, vanity_url or domain, thumbnail_image_large and card_url, which is all a card widget draws. Here is one real post from @FlutterDev after trimming (text abridged):
{
"id": "2127520443548520820",
"text": "Build a design system tailored to your brand in Flutter. (abridged)",
"createdAt": "Mon Nov 30 21:49:35 +0000 2026",
"author": {
"name": "Flutter",
"userName": "FlutterDev",
"avatar": "https://pbs.twimg.com/profile_images/1187814172307800064/MhnwJbxw_normal.jpg",
"blue": true
},
"counts": {
"replyCount": 2,
"retweetCount": 1,
"likeCount": 32,
"viewCount": 2908,
"bookmarkCount": 13
},
"urls": [],
"media": [
{
"type": "video",
"image": "https://pbs.twimg.com/media/HYZ4kWBWgAAdMpe.png",
"video": "https://video.twimg.com/amplify_video/2127520247271788544/vid/avc1/1920x1080/6bQVNMGl7V39EV77.mp4?tag=16",
"w": 720,
"h": 405
}
],
"card": null,
"quoted": null,
"repostedBy": null
}Step 2: the Dart model, shaped by real payloads
The model mirrors the proxy's slim shape. Three details come straight from the study. First, ids are strings in every one of the 855 tweets we pulled, and they should stay String in Dart: per the Dart number-representation docs, on the web an int is a JavaScript number and loses precision past 53 bits, and tweet ids are larger than that. Second, createdAt looks like Mon Nov 30 21:49:35 +0000 2026, which DateTime.parse does not accept; all 1,123 timestamps we checked (including nested reposts and quotes) had six space-separated parts and a +0000 offset, so a tiny parser that builds a UTC DateTime is enough. Third, every counter can be missing on older posts, so each one falls back to 0.
The only package is http (version 1.6.0 on pub.dev at the time of writing, published by dart.dev). Add it to pubspec.yaml under dependencies.
What we ran. Flutter and Dart were not installed on the machine used for this guide, so the Dart files below were not compiled or run by us; they are written against the standard Flutter widget APIs and the slim JSON shape above. The Python proxy and its trimming function were executed against the study data, and the same trimming code produced the byte counts in the table above.
// lib/tweet.dart (pubspec.yaml: dependencies: http: ^1.6.0)
class TweetMedia {
TweetMedia.fromJson(Map<String, dynamic> j)
: type = j['type'] as String? ?? 'photo', // photo | video | animated_gif
image = j['image'] as String? ?? '',
video = j['video'] as String?, // best mp4, null for photos
aspect = (j['w'] is num && j['h'] is num && j['h'] != 0)
? (j['w'] as num) / (j['h'] as num)
: 16 / 9;
final String type;
final String image;
final String? video;
final double aspect;
}
class LinkCard {
LinkCard.fromJson(Map<String, dynamic> j)
: title = j['title'] as String?,
domain = j['domain'] as String?,
image = j['image'] as String?,
url = j['url'] as String?;
final String? title, domain, image, url;
}
class Tweet {
Tweet({
required this.id,
required this.text,
required this.authorName,
required this.userName,
required this.avatar,
required this.blue,
required this.createdAt,
required this.replies,
required this.reposts,
required this.likes,
required this.views,
required this.media,
this.card,
this.quoted,
this.repostedBy,
});
// ids stay String: on Flutter web an int loses precision past 53 bits
final String id, text, authorName, userName, avatar;
final bool blue;
final DateTime createdAt;
final int replies, reposts, likes, views;
final List<TweetMedia> media;
final LinkCard? card;
final Tweet? quoted;
final String? repostedBy;
factory Tweet.fromJson(Map<String, dynamic> j) {
final a = (j['author'] as Map?)?.cast<String, dynamic>() ?? const <String, dynamic>{};
final c = (j['counts'] as Map?)?.cast<String, dynamic>() ?? const <String, dynamic>{};
int n(String k) => (c[k] as num?)?.toInt() ?? 0;
return Tweet(
id: j['id'] as String,
text: j['text'] as String? ?? '',
authorName: a['name'] as String? ?? '',
userName: a['userName'] as String? ?? '',
avatar: a['avatar'] as String? ?? '',
blue: a['blue'] == true,
createdAt: parseTwitterDate(j['createdAt'] as String? ?? ''),
replies: n('replyCount'),
reposts: n('retweetCount'),
likes: n('likeCount'),
views: n('viewCount'),
media: ((j['media'] as List?) ?? const [])
.map((m) => TweetMedia.fromJson((m as Map).cast<String, dynamic>()))
.toList(),
card: j['card'] == null ? null : LinkCard.fromJson((j['card'] as Map).cast<String, dynamic>()),
quoted: j['quoted'] == null ? null : Tweet.fromJson((j['quoted'] as Map).cast<String, dynamic>()),
repostedBy: j['repostedBy'] as String?,
);
}
}
// "Mon Nov 30 21:49:35 +0000 2026" is not ISO 8601, so DateTime.parse rejects it.
const _months = {
'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12,
};
DateTime parseTwitterDate(String s) {
final p = s.split(' ');
if (p.length != 6) return DateTime.now().toUtc();
final hms = p[3].split(':').map(int.parse).toList();
return DateTime.utc(int.parse(p[5]), _months[p[1]] ?? 1, int.parse(p[2]), hms[0], hms[1], hms[2]);
}Step 3: infinite scroll with ListView.builder and the cursor
Flutter's docs describe ListView.builder as appropriate for lists with a large or infinite number of children, and the builder is called only for the children that are actually visible. That is the timeline. The screen keeps a list of tweets, the current cursor and a has_next_page flag; a scroll listener asks for the next page when fewer than 800 pixels remain below the viewport, and a footer row shows a spinner, a retry button or "End of timeline".
Dedupe by id. In 3 of our 10 accounts, a later page repeated posts we had already received: 60 of 915 fetched rows were duplicates of an id already on screen. Without a Set<String> of seen ids the same post appears twice in the list and Flutter keys collide if you key cards by id.
Stop on an empty page, not only on the flag. Two timelines (@FlutterDev, @Google) ended with a page that returned zero tweets and has_next_page: false. The screen treats either signal as the end, so it never loops on an empty response. The median non-empty page held 20 tweets.
One request in flight. The _loading guard matters: a fast fling fires the scroll listener many times, and each duplicate call would bill another page. Pull-to-refresh clears the list, the seen-id set and the cursor, then loads page one again.
// lib/timeline_screen.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'tweet.dart';
import 'tweet_card.dart';
// The URL of YOUR proxy, not api.twitterapi.io. Never pass the API key with
// --dart-define: compile-time constants end up inside the app binary.
const feedUrl = String.fromEnvironment('FEED_URL', defaultValue: 'http://localhost:8080');
class FeedPage {
FeedPage(this.tweets, this.hasNext, this.cursor);
final List<Tweet> tweets;
final bool hasNext;
final String cursor;
}
Future<FeedPage> fetchFeed(String user, String cursor) async {
final uri = Uri.parse('$feedUrl/feed').replace(queryParameters: {'user': user, 'cursor': cursor});
final res = await http.get(uri).timeout(const Duration(seconds: 30));
if (res.statusCode != 200) throw Exception('feed returned ${res.statusCode}');
final body = jsonDecode(res.body) as Map<String, dynamic>;
return FeedPage(
(body['tweets'] as List).map((e) => Tweet.fromJson((e as Map).cast<String, dynamic>())).toList(),
body['has_next_page'] == true,
body['next_cursor'] as String? ?? '',
);
}
class TimelineScreen extends StatefulWidget {
const TimelineScreen({super.key, required this.user});
final String user;
@override
State<TimelineScreen> createState() => _TimelineScreenState();
}
class _TimelineScreenState extends State<TimelineScreen> {
final _scroll = ScrollController();
final _tweets = <Tweet>[];
final _seen = <String>{}; // pages can repeat ids: dedupe before adding
String _cursor = '';
bool _hasNext = true;
bool _loading = false;
Object? _error;
@override
void initState() {
super.initState();
_scroll.addListener(() {
if (_scroll.position.extentAfter < 800) _loadMore();
});
_loadMore();
}
@override
void dispose() {
_scroll.dispose();
super.dispose();
}
Future<void> _loadMore() async {
if (_loading || !_hasNext) return; // one request in flight, stop at the end
setState(() {
_loading = true;
_error = null;
});
try {
final page = await fetchFeed(widget.user, _cursor);
if (!mounted) return;
setState(() {
for (final t in page.tweets) {
if (_seen.add(t.id)) _tweets.add(t);
}
_cursor = page.cursor;
_hasNext = page.hasNext && page.tweets.isNotEmpty;
});
} catch (e) {
if (mounted) setState(() => _error = e);
} finally {
if (mounted) setState(() => _loading = false);
}
}
Future<void> _refresh() async {
if (_loading) return;
setState(() {
_tweets.clear();
_seen.clear();
_cursor = '';
_hasNext = true;
});
await _loadMore();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('@${widget.user}')),
body: RefreshIndicator(
onRefresh: _refresh,
child: ListView.builder(
controller: _scroll,
physics: const AlwaysScrollableScrollPhysics(),
itemCount: _tweets.length + 1, // +1 footer row
itemBuilder: (context, i) {
if (i < _tweets.length) return TweetCard(tweet: _tweets[i]);
if (_error != null) {
return ListTile(
title: const Text('Could not load tweets'),
trailing: TextButton(onPressed: _loadMore, child: const Text('Retry')),
);
}
if (_hasNext) {
return const Padding(
padding: EdgeInsets.all(24),
child: Center(child: CircularProgressIndicator()),
);
}
return const Padding(
padding: EdgeInsets.all(24),
child: Center(child: Text('End of timeline')),
);
},
),
),
);
}
}Step 4: the TweetCard widget, built from what real tweets contain
We counted how often each part of a tweet card is actually needed across the sample. Media is the common case, not the exception, and links and mentions appear in about half of all posts; quoted tweets are rare on organization timelines but still have to render.
Media details that shape the layout. Of 458 media items, 54.8% were photos, 44.1% videos and 1.1% animated GIFs. Their shapes vary: 286 were landscape, 140 portrait and 32 roughly square, so a fixed 16:9 box crops a large share of them. The card uses each item's original_info width and height, clamped between 0.75 and 2.0 so a tall clip cannot fill the screen. Videos carried a median of 5 variants (an HLS playlist plus several MP4 bitrates); the proxy hands the app the highest-bitrate MP4 so a player widget such as the video_player plugin (published by flutter.dev; per its page the backing player on Android is ExoPlayer) can open it on tap.
Text needs no truncation logic for normal posts. Visible text had a median of 140 characters and a 90th percentile of 274; only 1 post exceeded 280. Long-form X articles exist but appeared on 0.6% of posts, so a "Read article" link is enough for them.
// lib/tweet_card.dart
import 'package:flutter/material.dart';
import 'tweet.dart';
String compact(int n) {
if (n >= 1000000) return '${(n / 1000000).toStringAsFixed(1)}M';
if (n >= 1000) return '${(n / 1000).toStringAsFixed(1)}K';
return '$n';
}
String ago(DateTime t) {
final d = DateTime.now().toUtc().difference(t);
if (d.inMinutes < 60) return '${d.inMinutes}m';
if (d.inHours < 24) return '${d.inHours}h';
return '${d.inDays}d';
}
class TweetCard extends StatelessWidget {
const TweetCard({super.key, required this.tweet, this.nested = false});
final Tweet tweet;
final bool nested; // true inside a quoted-tweet box
@override
Widget build(BuildContext context) {
final t = tweet;
final muted = Theme.of(context).textTheme.bodySmall?.copyWith(color: Colors.grey);
final body = Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (t.repostedBy != null)
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Text('${t.repostedBy} reposted', style: muted),
),
Row(children: [
Flexible(
child: Text(t.authorName,
overflow: TextOverflow.ellipsis, style: const TextStyle(fontWeight: FontWeight.bold)),
),
if (t.blue)
const Padding(
padding: EdgeInsets.only(left: 4),
child: Icon(Icons.verified, size: 16, color: Colors.blue),
),
Flexible(
child: Text(' @${t.userName} \u00b7 ${ago(t.createdAt)}', overflow: TextOverflow.ellipsis, style: muted),
),
]),
if (t.text.isNotEmpty) Padding(padding: const EdgeInsets.only(top: 2), child: Text(t.text)),
if (t.media.isNotEmpty)
Padding(padding: const EdgeInsets.only(top: 8), child: MediaGrid(media: t.media)),
if (t.card != null && t.media.isEmpty)
Padding(padding: const EdgeInsets.only(top: 8), child: LinkCardView(card: t.card!)),
if (t.quoted != null && !nested)
Container(
margin: const EdgeInsets.only(top: 8),
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade700),
borderRadius: BorderRadius.circular(12),
),
child: TweetCard(tweet: t.quoted!, nested: true),
),
if (!nested)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
_stat(Icons.chat_bubble_outline, t.replies, muted),
_stat(Icons.repeat, t.reposts, muted),
_stat(Icons.favorite_border, t.likes, muted),
_stat(Icons.bar_chart, t.views, muted),
],
),
),
],
);
if (nested) return body;
return Padding(
padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),
child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
CircleAvatar(radius: 20, backgroundImage: t.avatar.isEmpty ? null : NetworkImage(t.avatar)),
const SizedBox(width: 10),
Expanded(child: body),
]),
);
}
Widget _stat(IconData icon, int n, TextStyle? style) => Row(children: [
Icon(icon, size: 16, color: Colors.grey),
const SizedBox(width: 4),
Text(compact(n), style: style),
]);
}
class MediaGrid extends StatelessWidget {
const MediaGrid({super.key, required this.media});
final List<TweetMedia> media;
@override
Widget build(BuildContext context) {
Widget tile(TweetMedia m) => Stack(fit: StackFit.expand, children: [
Image.network(m.image, fit: BoxFit.cover),
if (m.type != 'photo')
const Center(child: Icon(Icons.play_circle_fill, size: 48, color: Colors.white)),
]);
final radius = BorderRadius.circular(14);
if (media.length == 1) {
// use the real ratio, clamped so a tall portrait clip cannot fill the screen
final ratio = media.first.aspect.clamp(0.75, 2.0).toDouble();
return ClipRRect(borderRadius: radius, child: AspectRatio(aspectRatio: ratio, child: tile(media.first)));
}
return ClipRRect(
borderRadius: radius,
child: AspectRatio(
aspectRatio: 16 / 9,
child: GridView.count(
crossAxisCount: 2,
mainAxisSpacing: 2,
crossAxisSpacing: 2,
physics: const NeverScrollableScrollPhysics(),
childAspectRatio: media.length == 2 ? 8 / 9 : 16 / 9,
children: media.take(4).map(tile).toList(),
),
),
);
}
}
class LinkCardView extends StatelessWidget {
const LinkCardView({super.key, required this.card});
final LinkCard card;
@override
Widget build(BuildContext context) => Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade700),
borderRadius: BorderRadius.circular(14),
),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
if (card.image != null)
AspectRatio(aspectRatio: 1.91, child: Image.network(card.image!, fit: BoxFit.cover)),
Padding(
padding: const EdgeInsets.all(10),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
if (card.domain != null) Text(card.domain!, style: const TextStyle(color: Colors.grey, fontSize: 12)),
if (card.title != null) Text(card.title!, maxLines: 2, overflow: TextOverflow.ellipsis),
]),
),
]),
);
}
The repost trap: media lives inside retweeted_tweet
The single biggest rendering bug we found in the data is easy to miss in a mock-JSON clone. A repost's top-level object carries the "RT @..." text and, usually, no media. In our sample 237 of 855 posts were reposts; 179 of them had media inside retweeted_tweet.extendedEntities, and only 23 exposed media at the top level.
Read only the top level and your timeline shows media on 39.1% of posts; read the original inside each repost and it is 57.3%. For @Xbox, a repost-heavy account (66.0% reposts), the difference is 36.0% versus 88.0%. For @NASA it is 56.0% versus 87.0%. That is why the proxy unwraps reposts before trimming, and why the Dart model has a repostedBy field instead of a raw text prefix.
News publishers behave differently again: @verge posts were link cards on every post in our sample and @nytimes on 90.5%, so a news-reader style clone needs the link card widget more than the media grid.

What it costs to feed (and post from) the clone: TwitterAPI.io vs the official X API
On TwitterAPI.io, timeline and search reads are 15 credits per tweet returned, which is $0.15 per 1,000 tweets, with a 15-credit minimum per request: a full 20-post page costs $0.003 and an empty page costs the $0.00015 minimum. The official X API's pay-per-usage rate card on docs.x.com/x-api/getting-started/pricing lists $0.005 per post read and $0.010 per user read, with post reads capped at 3 million per monthly billing cycle and an Enterprise plan above that.
That is about 33x less per 1,000 tweets ($5 / $0.15). Two habits keep the bill small in a clone. Cache on the proxy: if many users open the same account, cache page one for a minute or two and serve it from memory; the API is billed per tweet returned, so ten thousand app opens on a cached page cost one page. Do not poll for new posts from the app: if you want a live feel, let the proxy check on a fixed schedule; a check that finds nothing costs the $0.00015 minimum, which is $6.48 a month at one check every 60 seconds or $1.30 at one every 5 minutes.
Rate limits while you build. Before the first payment the API allows 0.2 requests per second, one request every 5 seconds, which is enough for a single developer scrolling a test feed but not for a demo with several phones; paid accounts get 20 requests per second, 50 on Scale and 500 on Business. New accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days); see the pricing page for the current amount. Purchased credits never expire.
Posting from the clone. A clone usually has a compose screen. Reads need no X account, but posting does: write actions run through an authenticated session. One /twitter/user_login_v2 call ($0.10, with a proxy you supply) returns login_cookies, and each post through /twitter/create_tweet_v2 (or like, follow, delete) is 60 credits, $0.0006 per successful call; calls that return status: error are not charged. On the official X API a post created is $0.015 ($0.20 with a URL).
The same rule as reads applies, more strictly: the session cookie lives on your server, never in the Flutter app. The call acts as that account, so X can rate-limit, lock or suspend it; use only your own account, keep a normal human pace, expect to log in again when the session expires, and remember that X's automation rules apply. This is not a way around any limit. For a portfolio clone, the safest compose button writes to your own backend and leaves X untouched.
How we collected this
Question. Which tweet fields does a Flutter Twitter clone need to render real timelines, and how often is each card component used?
Accounts. Ten public organization timelines: @FlutterDev, @dart_lang, @Google, @github, @NASA, @SpaceX, @verge, @nytimes, @Xbox, @nvidia. They were chosen to mix developer, space, gaming, hardware and news publishers, because each group stresses a different widget.
Method and window. /twitter/user/last_tweets with userName, default includeReplies=false, newest first, up to 5 pages per account; the window is each account's recent posts at collection time, collected in 2026. 48 requests returned 915 rows, 855 unique posts after removing repeated ids, for about $0.14 in credits. Byte sizes are the re-serialized JSON of each tweet object, so they approximate what a proxy would forward before compression.
What the sample cannot show. Organization accounts repost and attach media more than a typical personal account, and replies are excluded by default, so a home-feed or reply-thread clone will see different shares. Ten accounts and a recent window are a sample, not a census; measure your own target accounts before you hard-code layout assumptions.
Privacy. Aggregates only. Only organization accounts are named; the authors of reposted and quoted posts are not analyzed or reported, and the committed sample rows carry no ids, URLs, text or handles of anyone else.
"""Feed proxy for a Flutter Twitter clone: the app calls this server, this server holds the API key.
Run: export TWITTERAPI_KEY=... then python3 proxy.py
App: GET http://<host>:8080/feed?user=NASA&cursor=
Only `requests` is needed (pip install requests); the server is the standard library.
"""
import json
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
import requests
BASE = "https://api.twitterapi.io"
API_KEY = os.environ["TWITTERAPI_KEY"] # stays on the server, never in the app binary
ALLOWED = {"FlutterDev", "dart_lang", "NASA", "github"} # accounts your app may show
def best_mp4(media):
variants = (media.get("video_info") or {}).get("variants") or []
mp4 = [v for v in variants if v.get("content_type") == "video/mp4"]
return max(mp4, key=lambda v: v.get("bitrate", 0))["url"] if mp4 else None
def slim_card(card):
if not card:
return None
vals = {b["key"]: b["value"] for b in card.get("binding_values") or []}
img = (vals.get("thumbnail_image_large") or {}).get("image_value") or {}
return {
"title": (vals.get("title") or {}).get("string_value"),
"domain": (vals.get("vanity_url") or vals.get("domain") or {}).get("string_value"),
"image": img.get("url"),
"url": (vals.get("card_url") or {}).get("string_value"),
}
def slim(t, nested=False):
"""Keep only what a TweetCard draws. Reposts are unwrapped to the original post."""
reposted_by = None
if t.get("retweeted_tweet") and not nested:
reposted_by = t["author"]["name"]
t = t["retweeted_tweet"]
text = t.get("text") or ""
rng = t.get("displayTextRange")
if isinstance(rng, list) and len(rng) == 2:
text = text[rng[0]:rng[1]] # drops the trailing t.co media link
a = t.get("author") or {}
media = []
for m in (t.get("extendedEntities") or {}).get("media") or []:
info = m.get("original_info") or {}
media.append({
"type": m.get("type"), # photo | video | animated_gif
"image": m.get("media_url_https"),
"video": best_mp4(m) if m.get("type") != "photo" else None,
"w": info.get("width"),
"h": info.get("height"),
})
return {
"id": t["id"],
"text": text,
"createdAt": t.get("createdAt"),
"author": {"name": a.get("name"), "userName": a.get("userName"),
"avatar": a.get("profilePicture"), "blue": a.get("isBlueVerified", False)},
"counts": {k: t.get(k, 0) for k in ("replyCount", "retweetCount", "likeCount", "viewCount", "bookmarkCount")},
"urls": [{"url": u.get("url"), "display": u.get("display_url"), "expanded": u.get("expanded_url")}
for u in (t.get("entities") or {}).get("urls") or []],
"media": media,
"card": slim_card(t.get("card")),
"quoted": slim(t["quoted_tweet"], nested=True) if t.get("quoted_tweet") and not nested else None,
"repostedBy": reposted_by,
}
def fetch_page(user, cursor=""):
r = requests.get(
f"{BASE}/twitter/user/last_tweets",
headers={"X-API-Key": API_KEY},
params={"userName": user, "cursor": cursor},
timeout=30,
)
r.raise_for_status()
body = r.json()
if body.get("status") != "success":
raise RuntimeError(body.get("msg"))
tweets = (body.get("data") or {}).get("tweets") or []
return {
"tweets": [slim(t) for t in tweets],
"has_next_page": bool(body.get("has_next_page")) and bool(tweets),
"next_cursor": body.get("next_cursor") or "",
}
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
u = urlparse(self.path)
q = parse_qs(u.query)
user = (q.get("user") or [""])[0]
if u.path != "/feed" or user not in ALLOWED:
return self.reply(404, {"error": "unknown feed"})
try:
self.reply(200, fetch_page(user, (q.get("cursor") or [""])[0]))
except Exception as e: # upstream error: let the app show a retry row
self.reply(502, {"error": str(e)})
def reply(self, code, obj):
data = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
if __name__ == "__main__":
ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever()Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.
Questions readers ask
Is there a Flutter Twitter clone on GitHub I can start from?
Yes. The widely forked one is Fwitter (github.com/TheAlphamerc/flutter_twitter_clone), MIT-licensed and built on Firebase, with feed, compose, profiles, notifications and chat screens. Course projects built on Appwrite with Riverpod also exist. All of them store their own users' posts; to show real X posts, keep the UI and replace the data layer with a proxy that calls /twitter/user/last_tweets.
Can my Flutter app call the Twitter (X) API directly?
It can, but it should not hold the key. Any key compiled into the app, including one passed with --dart-define, ships inside the binary and can be extracted. Run a small proxy that adds the X-API-Key header, restricts which accounts can be fetched, caches popular pages and trims the payload.
How do I implement infinite scroll for a tweet timeline in Flutter?
Use ListView.builder with a ScrollController. When position.extentAfter drops below a threshold, request the next page with the saved next_cursor, append only tweets whose id is not already in a Set<String>, and stop when has_next_page is false or a page comes back empty. Allow one request in flight at a time.
Why do retweets show no image in my clone?
Because the media lives inside retweeted_tweet. In our sample, 179 of 237 reposts had media inside the original post and only 23 at the top level. Unwrap reposts and render the original with a "reposted" header.
How do I parse the tweet createdAt date in Dart?
createdAt looks like Mon Nov 30 21:49:35 +0000 2026, which DateTime.parse rejects. Split on spaces, map the month name to a number and build DateTime.utc(year, month, day, h, m, s). Every timestamp we checked used the +0000 offset.
Should tweet ids be int or String in Dart?
String. On native platforms a Dart int is 64-bit, but on Flutter web it is a JavaScript number with 53 bits of integer precision, and tweet ids are larger. The API already returns ids as strings.
How much does it cost to show real tweets in a Flutter clone?
On TwitterAPI.io reads are $0.15 per 1,000 tweets, so a full 20-post page is $0.003 and an empty page is the $0.00015 minimum. The official X API lists $0.005 per post read, $0.10 for the same 20 posts. Caching page one on the proxy keeps repeated app opens from paying again.
Can the clone post tweets too?
Yes, through an authenticated session: /twitter/user_login_v2 ($0.10, with a proxy you supply) returns login_cookies, then /twitter/create_tweet_v2 is 60 credits ($0.0006) per successful call, and calls that return status: error are not charged. The call acts as that account, so X can rate-limit, lock or suspend it; keep a normal human pace and keep the session on your server.
Continue
- TwitterAPI.io docs: Get user last tweets (userName/userId, cursor, includeReplies, 20 per page, has_next_page, next_cursor)
- X developer docs: pay-per-usage pricing ($0.005 per post read, 3M monthly cap)
- Flutter API docs: ListView.builder for large or infinite lists
- pub.dev: http package (dart.dev)
- Dart docs: number representation (53-bit integers on the web)
- GitHub: Fwitter, a Flutter Twitter clone on Firebase (MIT)
- Twitter (X) API overview: endpoints, pricing and limits
- Build a Twitter clone with React and Next.js
- Render tweets in a React app
- Twitter (X) API user timeline endpoint guide
- Store tweets in Firebase with the Twitter (X) API
- How the X-API-Key header works
- TwitterAPI.io pricing and free starter credits
- 01B2B on Twitter (X) in 2026: Is It Worth It, and What Actually Works
- 02Twitter (X) Lead Generation: Finding and Qualifying Buyers with Search
- 03Twitter (X) Influencer Marketing: Find and Vet Creators With Data
- 04Twitter (X) and MongoDB: store tweets as documents, upsert by id, query them fast
- 05Supabase + Twitter (X) API: store tweets in Postgres with an Edge Function and pg_cron
- 06Build a Twitter (X) Clone in Next.js with Real Data
- 07Claude Routines: What They Are, Their Limits, and a Twitter (X) Watch Routine
- 08How to Use the OpenAI Agents SDK with the Twitter (X) API
Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.
Stop reading. Start building.
Starter credits cover real testing on real data. Google sign-in, no card, no application queue.
Get an API keyAlready building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.