forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bloc-text-editing-controller-in-flutter.dart
110 lines (97 loc) · 2.7 KB
/
bloc-text-editing-controller-in-flutter.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
abstract class Event {
const Event();
}
class SearchEvent extends Event {
final String searchString;
const SearchEvent(this.searchString);
}
class ClearSearch extends Event {}
class SearchBloc extends Bloc<Event, List<String>> {
static const names = ['foo', 'bar', 'baz'];
SearchBloc() : super(names) {
on<Event>((event, emit) {
if (event is SearchEvent) {
emit(names
.where((element) => element.contains(event.searchString))
.toList());
} else if (event is ClearSearch) {
emit(names);
}
});
}
}
class BlocTextEditingController extends TextEditingController {
SearchBloc? bloc;
BlocTextEditingController() {
addListener(() {
if (text.isEmpty) {
bloc?.add(ClearSearch());
} else {
bloc?.add(SearchEvent(text));
}
});
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
const largeStyle = TextStyle(fontSize: 30);
class _HomePageState extends State<HomePage> {
late final BlocTextEditingController _controller;
@override
void initState() {
_controller = BlocTextEditingController();
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
_controller.bloc = BlocProvider.of<SearchBloc>(context);
return Scaffold(
appBar: AppBar(
title: Text('Bloc Search in Flutter'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: BlocBuilder<SearchBloc, List<String>>(
builder: (context, state) {
return ListView.builder(
itemBuilder: (context, index) {
if (index == 0) {
// search field
return TextField(
decoration: InputDecoration(
hintText: 'Enter search term here...',
hintStyle: largeStyle,
),
style: largeStyle,
controller: _controller,
);
} else {
final name = state[index - 1];
return ListTile(
title: Text(
name,
style: largeStyle,
),
);
}
},
itemCount: state.length + 1, // +1 for search
);
},
),
),
);
}
}