こんにちは、株式会社Pentagonでエンジニアをしているtsurumiです。
目次
この記事の内容
- この記事がどんな記事なのか
- Flutterでのハッシュタグの実装方法についてまとめた記事です。
- なぜ書いているのか
- 今後新規の開発でハッシュタグを用いた実装が必要になりそうなので、事前調査のため。
- 誰に向けて書いているのか
- SNSのハッシュタグ機能をFlutterで作りたい人へ
- この記事の結論
- ハッシュタグ機能が実装できるようになる
hashtagableのインストール
- ハッシュタグ機能が実装できるようになる
- hashtagableを
pabspec.yaml
に追加
dependencies:
hashtagable: ^2.0.2+1
実装方法
- riverpod + freezed + state_notifierで実装してます。
class HashTagPage extends HookWidget {
const HashTagPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final state = useProvider(hashTagPageNotifierProvider);
final notfifier = useProvider(hashTagPageNotifierProvider.notifier);
return Scaffold(
appBar: AppBar(),
body: ListView(
children: [
HashTagTextField(
decoratedStyle: const TextStyle(fontSize: 14, color: Colors.blue),
basicStyle: const TextStyle(fontSize: 14, color: Colors.black),
onChanged: notfifier.onChangeForm,
),
HashTagText(
text: state.onChangeForm,
decoratedStyle: const TextStyle(fontSize: 22, color: Colors.red),
basicStyle: const TextStyle(fontSize: 22, color: Colors.black),
onTap: (text) {
Navigator.of(context).push<void>(
CupertinoPageRoute(
builder: (BuildContext context) => HashTagDetailPage(
text: text,
),
),
);
},
)
],
),
);
}
}
class HashTagDetailPage extends StatelessWidget {
const HashTagDetailPage({
Key? key,
required this.text,
}) : super(key: key);
final String text;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(text),
),
);
}
}
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:state_notifier/state_notifier.dart';
part 'hash_tag_page_notifier.freezed.dart';
final hashTagPageNotifierProvider =
StateNotifierProvider.autoDispose<HashTagPageNotifier, HashTagPageState>(
(ref) {
final hashTagPageNotifier = HashTagPageNotifier();
return hashTagPageNotifier;
});
@freezed
class HashTagPageState with _$HashTagPageState {
const factory HashTagPageState({
@Default('') String onChangeForm,
}) = _HashTagPageState;
}
class HashTagPageNotifier extends StateNotifier<HashTagPageState>
with LocatorMixin {
HashTagPageNotifier() : super(const HashTagPageState(onChangeForm: ''));
void onChangeForm(String v) {
state = state.copyWith(onChangeForm: v);
}
}
まとめ
以上でハッシュタグの実装ができます。
RichTextなどのWIdgetを使用してもできるそうですが、こちらのライブラリを使用すると楽に実装できます。
使用ライブラリ
dependencies:
hooks_riverpod: ^0.14.0+4
state_notifier: ^0.7.1
flutter_hooks: ^0.17.0
hashtagable: ^2.0.2+1