Skip to content

Instantly share code, notes, and snippets.

@burhanrashid52
Last active May 7, 2023 10:02
Show Gist options
  • Save burhanrashid52/8cb4487d07dfb2e417e8e48c434b9afb to your computer and use it in GitHub Desktop.
Save burhanrashid52/8cb4487d07dfb2e417e8e48c434b9afb to your computer and use it in GitHub Desktop.
ListenableBuilder Example
//Run from flutter version 3.10. Try beta or master channel
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MyListenableWidget(),
);
}
}
class MyWidget extends StatefulWidget {
const MyWidget({Key? key}) : super(key: key);
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
var value = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Stateful Widget'),
),
body: Column(
children: [
TextField(
decoration: const InputDecoration(
hintText: 'Type your message',
),
onChanged: (value) {
setState(() {
this.value = value;
});
},
),
ElevatedButton(
child: const Text('Send'),
onPressed: value.isEmpty
? null
: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'Send message "$value"',
),
),
);
},
)
],
),
);
}
}
class MyListenableWidget extends StatelessWidget {
MyListenableWidget({Key? key}) : super(key: key);
final textController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Listenable Builder'),
),
body: Column(
children: [
TextField(
controller: textController,
decoration: const InputDecoration(
hintText: 'Type your message',
),
),
ListenableBuilder(
listenable: textController,
builder: (context, widget) {
return ElevatedButton(
child: const Text('Send'),
onPressed: textController.text.isEmpty
? null
: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'Send message "${textController.text}"',
),
),
);
},
);
},
)
],
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment