Skip to content

Instantly share code, notes, and snippets.

@goderbauer
Created November 11, 2020 18:22
Show Gist options
  • Save goderbauer/b82efcb154c3fe1814a0d0b60d277def to your computer and use it in GitHub Desktop.
Save goderbauer/b82efcb154c3fe1814a0d0b60d277def to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyExample(),
);
}
}
class MyExample extends StatefulWidget {
MyExample({Key key, this.controller}) : super(key: key);
final TextEditingController controller;
@override
_MyExampleState createState() => _MyExampleState();
}
class _MyExampleState extends State<MyExample> with SingleTickerProviderStateMixin {
@override
void initState() {
super.initState();
// Add initial listener.
widget.controller.addListener(_textChanged);
}
@override
void didUpdateWidget(MyExample oldWidget) {
super.didUpdateWidget(oldWidget);
// Move listener.
if (widget.controller != oldWidget.controller) {
oldWidget.controller.removeListener(_textChanged);
widget.controller.addListener(_textChanged);
}
}
@override
void dispose() {
super.dispose();
// Remove listener.
widget.controller.removeListener(_textChanged);
}
void _textChanged() {
setState(() {
// The controller state changed.
});
}
@override
Widget build(BuildContext context) {
// Doing something useful with it.
return Text(widget.controller.text);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment